Monday, 12 March 2007

Cursors (I RANT)

Cursors. Satan's operand.
I hate them. There is nothing more annoying that working through someone's crap code which is failing, to find you need to decrypt their perverted thinking just to work out what is going on.
Apart from the fact that cursors are slow, I have never (I said 'NEVER') seen a case where cursors are necessary. In every case I've ever come across, there has been a better way of doing things. If you need to process data row by row, you can do this better and faster using a while loop, a select statement and a couple of marker variables.
If your reading this and you think I'm wrong, then you need to do a bit more research on set theory and then you may (I hope) come to understand why cursors are such terrible operations for a relational database.
I suspect cursors were invented to allow old COBOL programmers to be able to work with databases.
If I was offered a job where I never had to deal with cursors, and badly written code in general, I would gladly take a pay cut (well, just a small one) !

1 comment:

Paul Robinson said...

Basically I've never used cursors, or at least, not directly, that is to say, I've only used SELECT statements when I needed a piece of a database, either all of the fields or just some of them.

But the question comes up, are you using cursors because you have to, i.e. because there is no other way to access the data (only the cursor is accessible from the role or user connecting to the database), because you're required to by a convention ("we require that database access be by cursor"), or because you have to support legacy code that either you mistakenly wrote using cursors or the prior programmer(s) wrote using cursors, or some other reason?

If you have an alternative such that it's based on a fiat order as opposed to a technical requirement, perhaps you can ask to change it, show statistics on why a different method would be better.

Perhaps you can write both methods, and show where the method you use works faster, does fewer database calls, is easier to implement, is cheaper to use, doesn't cause cancer, etc.

Paul Robinson's Blog