Cursors - TSQL Tutorial: Declare Cursor Syntax
Cursors - TSQL Tutorial: Declare Cursor Syntax
In this chapter you can learn how to work with cursors using operations like declare
cursor, create procedure, fetch, delete, update, close, set, deallocate.
Cursor operations
Declare cursor
Create procedure
Open cursor
Close cursor
Fetch cursor
Deallocate cursor
Delete
Update
Declare cursors
Declare cursor Syntax:
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
[ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
[ TYPE_WARNING ]
FOR select_query_statement
[ FOR UPDATE [ OF column_name [ ,...n ] ] ] ;
Open cursors
Open cursor Syntax:
OPEN { { cursor_name } | cursor_variable_name }
Fetch cursors
Fetch cursor Syntax:
FETCH
[ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE { n | @nvar }
| RELATIVE { n | @nvar }
]
FROM
{ { cursor_name } | @cursor_variable_name }
[ INTO @variable_name [ ,...n ] ] ;
Deallocate cursors
When the cursor is deallocated, the data structures comprising the cursor are released by
Microsoft SQL Server.
DEALLOCATE @CursorName;
Update in cursors
Update in cursors example:
USE model;
GO
DECLARE test_cursor CURSOR LOCAL FOR
SELECT id, first_name, last_name, section
FROM dbo.students WHERE id = 2;
OPEN test_cursor;
FETCH test_cursor;
UPDATE dbo.students
SET section = 'Medicine'
FROM dbo.students
WHERE CURRENT OF test_cursor;
GO
Resources:
www.tsql.info/
www.tsql.info/cursors/cursors.php