'Sql cursor in infinite loop. What is wrong in this code?

Hi I am trying to loop for each employee id in table.

BEGIN
declare @empId nvarchar(50)
declare cur Cursor LOCAL for
select EmpId from EmployeeMaster 
open cur
fetch next from cur into @empId
     while @@FETCH_STATUS =0     
      begin      
       select  @empId  
      end   
close cur
END

This is my query in stored procedure. What is wrong with this? it is giving me first employee id within infinite loop. If i check while @@FETCH_STATUS =1 then no output given. just saying Command(s) completed successfully.



Solution 1:[1]

You need to add fetch command after select

BEGIN
declare @empId nvarchar(50)
declare cur Cursor LOCAL for
select EmpId from EmployeeMaster 
open cur
fetch next from cur into @empId
     while @@FETCH_STATUS =0     
      begin      
       select  @empId  
       fetch next from cur into @empId
      end   
close cur
END

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robert