tags:

views:

47

answers:

2

hi all tell me when should i use cursor?

thanks saj

+3  A: 

Ideally as little as possible. Cursors have quite a high inherent processing overhead

Either when

  1. The process you are doing can not be rewritten as a set based operation. (For example invoking DBCC DBREINDEX in turn on a list of tables)
  2. The set based operation has worse asymptotic complexity. For running aggregates the set based solution has quadratic complexity whereas the cursor workload grows linearly.

For this last case using a SQL CLR solution is significantly faster than using a standard cursor.

Martin Smith
+1  A: 

Please read: http://wiki.lessthandot.com/index.php/Cursors_and_How_to_Avoid_Them

You should be able to go your whole career without ever using a cursor unless you are a database admin.

HLGEM
While on principle I agree, I wouldn't say "whole career". Some times its just easier and faster to use a cursor than to find a way around them. If you can do it with a cursor in fifteen minutes instead of spending half a day for other alternatives, why wouldn't you? Of course providing that the cursor implementation is fast enough, but so far that has never been a problem for me.
Carlos