Question

I know that creating and using cursors in SQL is neither safe nor efficient but sometimes it's the only alternative. And right now it is the only alternative I have.

My question not how to avoid using cursors but how safe safe and what performance issues I will incur if the cursor is only operating on a temp table created on the fly within a stored procedure. I know cursors run slower than set operations and put a lock on tables that they're iterating. My temp table is a relatively small table containing just one field of type int and max 50 records.

DECLARE @pD int

DECLARE CurDB CURSOR FOR            
SELECT pD FROM #mD
open CurDB
fetch next from CurDB into @pD
etc...
Was it helpful?

Solution

Yes it's safe! And no! Cursors usually don't put a lock on the tables it's iterating. Also for better performance most of times you can declare your cursor with FAST_FORWARD (if they are no updating the table it's iterating over).

You can see the documentation about DECLARE CURSOR

Also 99.9% of times you can write a nice query with relational logic to do the same work a cursor can do, but usually faster and using less memory.

In fact cursor are no only clumsy but they perform bad at using memory, temp tables also ill consume RAM (or the tempdb, probably both).

Performance is not only about time and CPU cycles, it's about resources!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top