In this section, we shall learn about Cursor in SQL Server.
Cursor is a dynamically created database object to retrieve data from a result set (built using sql query) in row by row basis.
There are two types of cursor in SQL Server
Cursor scope can be declared as
We can also define how the cursor behaves to the data on which it is built, the cursor can be
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING ] FOR select_statement OPEN cursor_name
FETCH NEXT FROM cursor_name
[;]
Permission of cursor
Permission of declaring cursor is same as SELECT permission of the user.
Note that closing and deallocating the cursor is very important.
Below is a very simple cursor declared.
DECLARE @AutoId int
DECLARE @FullName varchar(100)
-- Step 1
DECLARE MyDetailsCursor CURSOR FOR
SELECT AutoId, FirstName + ' ' + LastName FROM PersonalDetails
WHERE AutoId > 1100;
-- Step 2
OPEN MyDetailsCursor
-- Step 3
FETCH NEXT FROM MyDetailsCursor INTO @AutoId, @FullName
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT CAST(@AutoId as varchar(20))+ ' -> ' + @FullName
FETCH NEXT FROM MyDetailsCursor INTO @AutoId, @FullName
END
-- Step 4
CLOSE MyDetailsCursor
-- Step 5
DEALLOCATE MyDetailsCursor
This will print data in Message window that looks something like below.
To know different types of cursor, read below posts.