0% found this document useful (0 votes)
3 views6 pages

Cursors

Database sql cursors

Uploaded by

zenandecewuka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

Cursors

Database sql cursors

Uploaded by

zenandecewuka
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

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.

When using a cursor you must follow these steps:

1. Declare a cursor that defines a result set.


2. Open the cursor to establish the result set.
3. Fetch the data into local variables as needed from the cursor, one row at a time.
4. Close and deallocate the cursor when done.

The basic syntax of using a cursor is as follows:

/*
declare all variables that are required
Fields and values that are retrieved via the cursor must
Be stored in variables
*/

/*
declare a cursor
*/

DECLARE cursor_name cursor FOR


/*
Open and populate the cursor
*/
OPEN cursor_name
/*
Fetch a row from the cursor into one or more variables
*/
FETCH NEXT FROM cursor_name
INTO /*previously declared variables*/
/*these variables must be in the same order as the
Fields selected in your select query used to populate
The 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

/*Close the cursor*/


CLOSE cursor_name
/*deallocate the cursor*/
DEALLOCATE cursor_name

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;

DECLARE cursor_product CURSOR


FOR SELECT
product_name,
list_price
FROM
production.products;

Next, open the cursor:

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;

Finally, deallocate the cursor to release it.


DEALLOCATE 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:

DECLARE @name VARCHAR(50) -- database name


DECLARE @path VARCHAR(256) -- path for backup files
DECLARE @fileName VARCHAR(256) -- filename for backup
DECLARE @fileDate VARCHAR(20) -- used for file name

SET @path = 'C:\Backup\'

SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)

DECLARE db_cursor CURSOR FOR


SELECT name
FROM MASTER.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb')

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

FETCH NEXT FROM db_cursor INTO @name


END

CLOSE db_cursor
DEALLOCATE db_cursor

DECLARE @AccountID INT


DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT Account_ID
FROM Accounts
OPEN @getAccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
END
CLOSE @getAccountID
DEALLOCATE @getAccountID

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

Fetch NEXT FROM MY_Cursor INTO @VAR1Number, @VAR2DateTime, @VarLongText


While (@@FETCH_STATUS = 0)
BEGIN
IF (@@FETCH_STATUS <> -2)
---You Can Use the values to build a new query or look up additional values
--- This displays the assign to field from OtherTable

SELECT o.assignto, S.Event


FROM OtherTable O, Sometable S
WHERE o.eventid = s.id
ORDER BY o.assignto

FETCH NEXT FROM MY_CURSOR INTO @VAR1Number, @VAR2DateTime ,@VarLongText


END
CLOSE MY_CURSORr
DEALLOCATE MY_CURSOR
GO

References
1. MSDN Library
2. https://www.sqlservertutorial.net/sql-server-stored-procedures/sql-server-cursor/

4|Page

You might also like