Welcome to SqlAdvice Sign in | Join | Help

Sql Server Cursor Template

This is a template that I have been using in SQL

server for when I do have to write cursors.  Notice that there is only one fetch statement in there which is much slicker than the typical method of initially doing a fetch, with a while condition of while (@@fetch_status <> 0) and then another fetch in the while loop.  This obviously seemed tedious and too much code for me as I could never remember to change the fetch statement in both parts.  So I started using the template below...notice the while (1=1) and then the fetch inside with a break if it is the end of the cursor.  When I first saw this I couldn't believe it took me so long to come up with something like this.  Let me know if you have any tweaks or suggestions.

 

declare @myvariable varchar(50) declare mycursor cursor forward_only for Select field1 from mytable open mycursor while (1=1) begin fetch next from mycursor into @myvariable if @@fetch_status <> 0 break; end close mycursor deallocate mycursor

del.icio.us Tags: , ,
Published Wednesday, July 18, 2007 11:07 PM by gstark
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

Thursday, April 17, 2008 8:57 AM by Traco

# re: Sql Server Cursor Template

I agree that this template is nicer that the traditional one and i use one that is exactly the same except that i use a fast_forward cursor instead. I heard they are better but i might be wrong.

I also notice that you use lower case keywords, i wish more sql developers would do that.

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below