Looping in MSSQL with Variable

sometimes, we need a loop within a query on MSSQL.

we can use a temporary table or cursor.

However, in simple cases we can switch to using table type of variable. more simple and faster.

declare @EmpIDList table (Emp_ID int,employee varchar(25))

declare @i int

declare @empName varchar(25)

insert into @EmpIDList

SELECT EmpID,employeeName

FROM Employee

select @i = min(Emp_ID),@empName from @EmpIDList

while @i is not null

begin

print @employee;

— your script

end

Leave a comment