Sql Server Cursor Variable


A cursor is a set of rows together with a pointer that identifies a current row.

In other word, Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, its like recordset in the ASP and visual basic.

Typical syntax of cursor is


DECLARE @fName varchar(50), @lName varchar(50)

DECLARE cursorName CURSOR -- Declare cursor
FOR
Select firstName, lastName FROM myTable

OPEN cursorName -- open the cursor

FETCH NEXT FROM cursorName

   INTO @fName, @lName
   PRINT @fName + ' ' + @lName --print name

WHILE @@FETCH_STATUS = 0
BEGIN

   FETCH NEXT FROM cursorName
   INTO @fName, @lName

   PRINT @fName + ' ' + @lName --print name
END

CLOSE cursorName -- close the cursor
DEALLOCATE cursorName -- Deallocate the cursor
Related Posts Plugin for WordPress, Blogger...