Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Always close your cursor

5.00/5 (1 vote)
13 Oct 2011CPOL 4.9K  
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:

SQL
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)