What is cursor in SQL Server?

 Posted by Raja on 12/14/2008 | Category: Sql Server Interview questions | Views: 126961
Answer:

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
LOCAL SCROLL STATIC
FOR
Select firstName, lastName FROM myTable
OPEN cursorName -- open the cursor
FETCH NEXT FROM cursorName
INTO @fName, @lName
PRINT @fName + ' ' + @lName -- print the name
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM cursorName
INTO @fName, @lName
PRINT @fName + ' ' + @lName -- print the name
END

CLOSE cursorName -- close the cursor
DEALLOCATE cursorName -- Deallocate the cursor


To know more about cursor, see
http://www.mssqlcity.com/Articles/General/UseCursor.htm


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Alok on: 1/18/2013 | Points: 10
can we call cursor from front end
Posted by: Sheonarayan on: 11/12/2015 | Points: 10
No, we can't call cursor from front end, you will need to keep the cursor code in Stored procedure and then you can call the stored procedure that will internally call the cursor.

Thanks
Posted by: Rajeshatkiit on: 12/17/2015 | Points: 10
Please refer this for more info.
http://www.codeproject.com/Tips/277847/How-to-use-Cursor-in-Sql

Login to post response