SQL Server CURSOR and it’s Life Cycle
A CURSOR in SQL is a database object that contains a set of records that you can traverse one-by-one, rather than the SET as a whole.
SQL is a set-based language and produces a complete result set, and the SQL queries works on this complete set only, and not on individual rows. But there are times when the results are best processed one row at a time. Opening a cursor on a result set allows processing the result set one row at a time. You can assign a cursor to a variable or parameter with a cursor data type.
CURSOR in SQL language gives you the flexibility to traverse records like the way you do in other programming languages with iterators and for-loop.
–> A simple Cursor life cycle with minimum definition:
USE [AdventureWorks] GO -- Returns -3 SELECT CURSOR_STATUS('global','myCursor') AS 'Before Declare' DECLARE myCursor CURSOR FOR SELECT ContactID, FirstName, LastName FROM Person.Contact WHERE ContactID BETWEEN 100 and 102 -- Returns -1 SELECT CURSOR_STATUS('global','myCursor') AS 'After Declare' DECLARE @ContactID INT, @FirstName VARCHAR(50), @LastName VARCHAR(50) OPEN myCursor -- Returns 1 SELECT CURSOR_STATUS('global','myCursor') AS 'Open Cusrsor' FETCH NEXT FROM myCursor INTO @ContactID, @FirstName, @LastName WHILE @@fetch_status=0 BEGIN -- SQL Statements with logic inside SELECT @ContactID, @FirstName, @LastName FETCH NEXT FROM myCursor INTO @ContactID, @FirstName, @LastName END -- Returns 1 SELECT CURSOR_STATUS('global','myCursor') AS 'While loop exited, all rows iterated' CLOSE myCursor -- Returns -1 SELECT CURSOR_STATUS('global','myCursor') AS 'Cursor is Closed' DEALLOCATE myCursor -- Returns -3 SELECT CURSOR_STATUS('global','myCursor') AS 'Cursor Deallocated'
Categories: Datatypes, SQL Tips
@@FETCH_STATUS, Cursor, CURSOR_STATUS, DEALLOCATE, DECLARE CURSOR
Comments (0)
Trackbacks (1)
Leave a comment
Trackback
-
July 29, 2011 at 9:56 amTSQL Interview Questions – Part 2 « SQL Server Programming, Tips & Tricks