SQL CURSOR Performance – SQL For Programmers

Last week I showed how to use the SQL CURSOR to loop through records in a database.  In that article I mentioned that you want to avoid using the CURSOR if you can because it has performance problems.

The article was posted on DZone where a self-proclaimed SQL guru picked it up and left a comment basically stating an alternate way of looping through records that would do the same thing but didn’t require the CURSOR.  What he suggested was the common practice of doing something like this:

SELECT TOP 1 @field1=Field1,
   @field2=field2, @key=keyfield(s)
   FROM TABLE ORDER BY keyfield(s)
WHILE @key /*appropriate logic
         to verify there is a record */
BEGIN
  /* processing here */
  SET @lastKey=@key
  SELECT TOP 1 @field1=Field1,
   @field2=field2, @Key=keyfield(s)
   FROM TABLE WHERE @lastKey < keyfield(s)
END

Note: this is a rough outline of the code.  The key point is that you are doing a select for the next record up in order from the one you just retrieved and you are doing it with nothing but select statements.

Also, keep in mind that keyfield(s) could be one, or multiple fields and that the field(s) should be unique.  Otherwise this won’t work.

If you need to sort in an order other than the primary key, just make keyfield(s) a composite key with the sort order fields first and the primary key last.  Ie assuming all of the following fields are strings, keyfield(s) = field1 + field2 + primaryKeyField.

Instead of doing TOP 1, you could also do a select for the MINimum value of the remaining keys.

And it works for most cases.

However, in researching this post, I also ran across this article:

http://www.sqlteam.com/article/cursor-performance

The gist of the article is that while everyone knows you aren’t supposed to use CURSORS because they are so slow, you need to TEST your solution to make sure that in this particular case it really is faster.

But like I stated when I started this series, my job is to get you beyond SELECT, INSERT, UPDATE, and DELETE statements so that you can do more on the server side, not to turn you all into DBAs who know where all of these performance gotchas are.

Related Post

2 Responses to “SQL CURSOR Performance – SQL For Programmers”

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail

Bear