Search code examples
sqlinfinite-loopdatabase-cursor

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

  • 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