T-SQL: A Simple Example Using a Cursor
April 23, 2013 2 Comments
In SQL Server the cursor is a tool that is used to iterate over a result set, or to loop through each row of a result set one row at a time. It may not be the best way to work with a set of data, but if you need to loop row by agonizing row (RBAR) in a T-SQL script then a cursor is one way of doing it.
Note: If you are new to SQL Server and come from an Oracle background, you should know that cursors on SQL Server are different from those on Oracle.
Before creating the cursor, we will just start with a simple query that will end up being used in the cursor.
USE AdventureWorks2008; GO SELECT BusinessEntityID, Name FROM Sales.Store;
Which looks something like this:
Now to convert it to a cursor, instead of just a select statement.
Step 1: Declare variables to hold the output from the cursor.
</p> DECLARE @BusinessEntityID as INT; DECLARE @BusinessName as NVARCHAR(50);
Step 2: Declare the cursor object;
DECLARE @BusinessCursor as CURSOR;
Step 3: Assign the query to the cursor.
SET @BusinessCursor = CURSOR FOR SELECT BusinessEntityID, Name FROM Sales.Store;
Step 4: Open the cursor.
OPEN @BusinessCursor;
Step 5: Fetch the first row.
FETCH NEXT FROM @BusinessCursor INTO @BusinessEntityID, @BusinessName;
Step 5: Loop until there are no more results. In the loop print out the ID and the name from the result set and fetch the net row.
WHILE @@FETCH_STATUS = 0 BEGIN PRINT cast(@BusinessEntityID as VARCHAR (50)) + ' ' + @BusinessName; FETCH NEXT FROM @BusinessCursor INTO @BusinessEntityID, @BusinessName; END
Step 6: Close the cursor.
CLOSE @BusinessCursor;
Step 7: Deallocate the cursor to free up any memory or open result sets.
DEALLOCATE @BusinessCursor;
Now putting it all together:
DECLARE @BusinessEntityID as INT; DECLARE @BusinessName as NVARCHAR(50); DECLARE @BusinessCursor as CURSOR; SET @BusinessCursor = CURSOR FOR SELECT BusinessEntityID, Name FROM Sales.Store; OPEN @BusinessCursor; FETCH NEXT FROM @BusinessCursor INTO @BusinessEntityID, @BusinessName; WHILE @@FETCH_STATUS = 0 BEGIN PRINT cast(@BusinessEntityID as VARCHAR (50)) + ' ' + @BusinessName; FETCH NEXT FROM @BusinessCursor INTO @BusinessEntityID, @BusinessName; END CLOSE @BusinessCursor; DEALLOCATE @BusinessCursor;
This should give you a quick overview of how to quickly build and use a cursor on Microsoft SQL Server. The example shown was run on SQL Server 2008, and works the same on SQL Server 2005 or 2012.
Enjoy!







