Cursor
Cursor
▪ In SQL Server, a cursor is a database object used to retrieve and manipulate data row
by row, rather than fetching the entire result set at once.
▪ Cursors are primarily used in situations where set-based operations are not feasible or
efficient, such as when processing data in a procedural manner or when performing
row-level operations based on specific conditions.
How a cursor works in SQL Server:
▪ Declare Cursor: You declare a cursor by specifying a SELECT statement that defines
the result set to be processed.
▪ Open Cursor: After declaring the cursor, you open it to establish the result set.
▪ Fetch Cursor: Once the cursor is open, you fetch rows from the result set one at a time,
usually in a loop. Each fetch operation retrieves the next row from the result set.
▪ Process Data: As you fetch each row, you can perform operations or calculations based
on the data in that row.
▪ Close Cursor: After you have finished processing all the rows, you close the cursor to
release the resources associated with it.
▪ Deallocate Cursor: Optionally, you can deallocate the cursor to remove it from
memory entirely.
Types of Cursor:
There are two main types: implicit cursors and explicit cursors.
Implicit Cursors: Implicit cursors are automatically created by the SQL Server database
engine whenever a SELECT, INSERT, UPDATE, or DELETE statement is executed.
These cursors are managed internally by the database engine, and you don't have direct control
over them. Implicit cursors are handy for single-row operations where you don't need to process
multiple rows explicitly.
Example:
Select * From Employee
--Cursor Start from Here
DECLARE @FirstName VARCHAR(50)
DECLARE @LastName VARCHAR(50)
DECLARE @Email VARCHAR(100)
DECLARE @Phone VARCHAR(20)
DECLARE @Department VARCHAR(50)
DECLARE @Position VARCHAR(50)
DECLARE @Salary DECIMAL(10, 2)
OPEN EmployeeCursor
OPEN StudentCursor
FETCH NEXT FROM StudentCursor INTO @ID, @FirstName, @LastName, @Class, @Grade, @Email,
@Mobile, @City
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'ID: ' + CAST(@ID AS VARCHAR(10)) + ', Name: ' + @FirstName + ' ' +
@LastName + ', Class: ' + @Class + ', Grade: ' + @Grade + ', Email: ' + @Email + ',
Mobile: ' + @Mobile + ', City: ' + @City
FETCH NEXT FROM StudentCursor INTO @ID, @FirstName, @LastName, @Class, @Grade,
@Email, @Mobile, @City
END
CLOSE StudentCursor
DEALLOCATE StudentCursor