65.9K
CodeProject is changing. Read more.
Home

Always close your cursor

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Oct 13, 2011

CPOL
viewsIcon

4930

An alternative (simpler way :) ) is:BEGIN TRANDECLARE IdCursor CURSOR FOR SELECT Id FROM MyTable OPEN IdCursor FETCH NEXT FROM IdCursor INTO @CurrentIdWHILE (@@FETCH_STATUS) = 0 BEGIN -- do work IF @@error 0...

An alternative (simpler way :) ) is:

BEGIN TRAN

DECLARE IdCursor CURSOR FOR SELECT Id FROM MyTable
            
OPEN IdCursor
        
FETCH NEXT FROM IdCursor INTO @CurrentId
WHILE (@@FETCH_STATUS) = 0
    BEGIN   
        
    -- do work               
     IF @@error <> 0
     BEGIN 
      CLOSE IdCursor
      DEALLOCATE IdCursor    
      GOTO err
     END
                    
    FETCH NEXT FROM  IdCursor INTO @CurrentId
END -- end cursor

CLOSE IdCursor
DEALLOCATE IdCursor	
			
   
COMMIT TRAN
RETURN 0 -- success

err:
 
ROLLBACK TRAN 
RETURN 1   -- error