SQL Cursors

In SQL, a cursor lets you process data on a row by row basis.  As we’ve seen, SQL is really good at manipulating data sets.  We can group many rows together, update many rows at the same time, delete many rows at the same time, etc.  However, instead of performing a single action on a set of rows we might want to loop through a list of rows and process along the way.

Syntax

Below is the general syntax for a cursor:

The first DECLARE is defining a variable (@AuthorID).  Variables have to begin with @ and can be given a value in the declaration statement.  An example of this would be:

The next DECLARE is declaring the cursor.  This cursor has the name c1 and will be read only.  This is important – if we are only going to be reading data, we want to be sure to set the cursor as read_only.  This will help us imporve performance.  The SELECT statement below it is the process that we want to use to loop through every row.  Note you must have the FOR statement before the SELECT statement.

Next, the OPEN statement executes the cursor’s SELECT statement and puts the result in a set.

The FETCH command returns one row from the result and puts it into the @AuthorID variable.  We could fetch multiple columns and put them into multiple variables if we wanted (assuming we selected multiple in the cursor definition, of course!).

Next, the line

tells SQL that we want to continue doing this until there are no more rows.  In other words, FETCH_STATUS will be 0 until there are no more rows.

Next, the lines within the BEGIN/END will loop through the @AuthorID variable and print each @AuthorID.

Obviously, there are much more efficient ways to do this within SQL.  This example is just a basic one to get an idea of the syntax.  In general, if you can avoid using a cursor, you probably should because they can be so slow.

Have questions or suggestions?  Please feel free to comment below or contact me.

Leave a Reply

Your email address will not be published. Required fields are marked *