Aaron Bertrand [SQL Server MVP] (ten.xoc@dnartreb.noraa) writes:
> This sounds suspiciously like homework.
Why on earth would anyone give homework about the cursor types in SQL
Server? In such case that teacher should be flogged officially!
> Did you bother to look at the topic DECLARE CURSOR in Books Online?
If he did, and did ont get it, I am not going to blame him. I'm still
not sure that I have after all these years.
I will try to explain to Somu, the best as I can.
There are six cursor types: SCROLL, INSENSITIVE, STATIC, FAST_FORWARD,
KEYSET and DYNAMIC. Of hese the first two are put before the CURSOR
keyword, as they are ANSI-compliant, whereas the other are proprietary.
The easiest types to understand are STATIC and INSENSITIVE. As far as they
are the same. And while INSENSITIVE is ANSI-compliant, you will prefer
to use STATIC, as this permits you to use the LOCAL keyword. This causes
the cursor to goes away when the scope it was created in exits.
In a STATIC/INSENSITIVE cursor, the query is run when you DECLARE the
cursor, and the result is put in an area in tempdb. When you fetch rows,
you fetch from this area. This is very nice, because you know exactly
which rows you work with, and nothing can happen when you run the cursor.
In a DYNAMIC cursor, the query in the DECLARE statement is run every
time you say FETCH. As you can imagine, this can be very expensive if the
query is poorly written. And if the query uses indexes, iterating
over all rows, is a lot slower with a dynamic cursor than with a static
cursor, despite the latter having the overhead of copying the rows.
Beware that DYNAMIC is the default type!
In a KEYSET cursor, the query is run at DECLARE as with a static cursor,
but only the *keys* are stored in tempdb. (Please don't ask me, how those
keys are identified!). Then remaining rows are queried as you loop through
the cursor.
I will have to leave SCROLL and FAST_FORWARD to someone else.
In the very most cases, a static cursor is what you want. I recently
had a case where I realised that a dynamic cursor gave me better
performance. This was because of potentially hundreds of thousands
of rows, I would typically only need to read five. But, no, I did not
use a dynamic cursor, I preferred roll the loop on my own, so that I
had full control of what is going on.
--
Erland Sommarskog, SQL Server MVP, esquel.DeleteThis@sommarskog.se
Links for SQL Server Books Online:
SQL 2008:
http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005:
http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
SQL 2000:
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx >> Stay informed about: cursor types difference