Cursors
Cursors
Contents
Cursors .................................................................................................................................................... 1
Step-by-step example ............................................................................................................................. 2
More examples ....................................................................................................................................... 3
References .............................................................................................................................................. 4
Cursors
In SQL, a cursor can be used to define a result set and then perform complex operations on that result
set on a row by row basis. A cursor points to one row at a time and can only move in the forward
direction.
/*
declare all variables that are required
Fields and values that are retrieved via the cursor must
Be stored in variables
*/
/*
declare a cursor
*/
/*
SQL Server provides the @@FETCHSTATUS function that returns the status of
the last cursor FETCHstatement executed against the cursor;
If @@FETCHSTATUS returns 0, meaning the FETCH statement was successful. You
can use the WHILE statement to fetch all rows from the cursor as shown in
the following code
*/
WHILE @@fetch_status = 0
BEGIN
/*
perform required operations on data
*/
1|Page
FETCH NEXT FROM cursor_name
INTO /*previously declared variables*/
END
Step-by-step example
Suppose you have the following entity:
First, declare two variables to hold product name and list price, and a cursor to hold the result of a
query that retrieves product name and list price from the production.products table:
DECLARE
@product_name VARCHAR(MAX),
@list_price DECIMAL;
OPEN cursor_product;
Then, fetch each row from the cursor and print out the product name and list price:
FETCH NEXT FROM cursor_product INTO
@product_name,
@list_price;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @product_name + CAST(@list_price AS varchar);
FETCH NEXT FROM cursor_product INTO
@product_name,
2|Page
@list_price;
END;
After that, close the cursor:
CLOSE cursor_product;
More examples
The following is a simple example of a cursor which can be used to make a backup of all databases
on the server:
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
SET @fileName = @path + @name + '_' + @fileDate + '.BAK'
BACKUP DATABASE @name TO DISK = @fileName
CLOSE db_cursor
DEALLOCATE db_cursor
3|Page
CREATE PROCEDURE USER_DATA_CURSOR
@StartDate DateTime, @EndDate DATETIME
AS
DECLARE MY_CURSOR Cursor
FOR
Select ID, EventDate, Event
From Sometable
where EVENT in ('Reboot_System', 'Failed_Login','Failed_Service')
and
EventDate Between @StartDate and @EndDate
Open My_Cursor
DECLARE @VAR1Number DateTime, @VAR2DateTime DATETIME @VarLongText LongText
References
1. MSDN Library
2. https://www.sqlservertutorial.net/sql-server-stored-procedures/sql-server-cursor/
4|Page