Suppose that I have a query that really must be either a cursor or a while loop. What criteria can be used to judge which should be used?
Notably not a duplicate of this question. I'm not trying to ask what the pros/cons of each option is. I'm assuming that I already know that and I'm asking how to come to a decision between the two options when stuck.
A lot of is comes down to personal preference or whether the other developers you work with have a visceral reaction to seeing a cursor. Personally, the only time I use a cursor is when it can replace having to declare a temporary table with a RID on it, insert rows into it, then do a
WHILEloop till@RID <= @MaxRIDAnd even then, the main reason I like them is it's easier to write a code snippet to loop using a cursor than it is to stub out the table.
So basically, if I have a scenario where I would have to do something like the following to use a
WHILEloop...I might replace it with...
That's about it. But really, don't underestimate the amount of revulsion many database developers have to cursors. Their logic is clunky, it's sort of hard to understand why you need a
local fast_forwardcursor for them to be acceptable, and there are so many more ways to abuse cursors than to use them properly, that most people I know just steer clear of them.If you're in doubt, I would reach for a
WHILEloop instead as, even in the best of circumstances, it will perform the same function as alocal fast_forwardcursor, and be immediately recognizable to other database developers. Unless of course you're working with a crew of people who like cursors better in which case, there's your answer.