Click here to Skip to main content
15,892,161 members
Articles / Database Development / SQL Server

Always close your cursor

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
13 Oct 2011CPOL 32.2K   2  
When cursors are inside transaction, it is sometimes easy to forget to close the cursor

Alternatives

Members may post updates or alternatives to this current article in order to show different approaches or add new features.

Please Sign up or sign in to vote.
13 Oct 2011Elina Blank
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...
Please Sign up or sign in to vote.
18 Oct 2011Kabwla.Phone
You also might want to look into the "LOCAL" keyword.This limits the scope of the cursor to the context in which it is created.DECLARE IdCursor CURSOR LOCAL FOR SELECT Id FROM MyTableThis is beneficial for many reasons.
Please Sign up or sign in to vote.
18 Oct 2011Elina Blank
To see the default value of the cursor scope:select * from sys.databases(if value of "is_local_cursor_default" is 0 then scope id global, otherwise it is local).The scope is GLOBAL by default (for compatibility reasons).To change default scope use following:ALTER DATABASE...

License

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


Written By
Software Developer (Senior) The Code Project
United States United States
Elina joined the Code Project team as a software developer in order to make the site run even smoother than it is now. She will also take care of making wishes and promises on the site improvements come to the light sooner than later. When not at work, she enjoys being with her family and wishes there will be at least 30 hours in a day Smile | :)

Comments and Discussions