Wednesday, October 21, 2009

How to avoid SQL cursors

Good article on sqlbook.com about how to avoid cursors. In short, there are two ways which the article suggests

1. Using temporary table with auto generated ID column and loop it through a while loop
2. Use SQL functions when possible to do calculation on a column

Read it here

I saw different articles on sites about the performance comparison between cursors and using while loop. Some places it made sense to use a cursor but the drawback is that it locks the table where while loops using temporary tables won't.

Due to its syntax and de-allocation procedure, I have never really tried using cursors which, not using them seems like a good practice according to some SQL experts. Read today on a site that one interviewer would ask people the syntax of using cursors and if they knew then he would consider it as negative since he wouldn't want people on his team to use them and knowing the syntax means that you use them :)

No comments: