Wednesday, October 3, 2012

Cursors are almost never the answer...

Over the years, I've been amazed at how many times I encounter the use of cursors, while loops, etc.

I confess I fall into the trap of using a while loop more often than I'd care to admit.

Stated bluntly, using cursors is a procedural crutch.  Here we have a database engine written to perform operations efficiently on massive amounts of information (millions, maybe billions of rows) and what do people tend to do?

They try to perform a series of operations on one row at a time, using the same procedural thinking that they learned in computer science 101.

Yes, I admit it, sometimes it is easier to think that way, but that is not the point.

The point is to ask 'what is the most efficient way?'!

Numerous posts are sprinkled all over the internet by heavyweights such at Itzak Ben-Gan and Paul Nielsen that scientifically prove that the cursor and/or while loop procedural approach rarely if ever is justified.

There is almost no problem space these techniques can be applied to that cannot be solved more efficiently with a little careful thought and the proper application of table joins.

Think about it.