Cursor is a database objects to retrieve data from a result set one row at a time, instead of the T-SQL commands that operate on all the rows in the result set at one time.
We use cursor when we need to update records in a database table in singleton fashion means row by row.
Life Cycle of Cursor:
Declare Cursor:
Syntax:
DECLARE cursor_name CURSOR
FOR select_statement --define SQL Select statement
FOR UPDATE [col1,col2,...coln] --define columns that need to be updated
Open Cursor:
Syntax:
OPEN [GLOBAL] cursor_name --by default it is local
Fetch Cursor:
Syntax:
INTO @Variable_name[1,2,..n]
Close Cursor
Syntax:
CLOSE cursor_name --after closing it can be reopen
Deallocate Cursor
Syntax:
DEALLOCATE cursor_name --after deallocation it can't be reopen
An Example of Cursor:
create PROCEDURE sp_rohit
AS
BEGIN
declare @empCode as varchar(30)
declare @emp_name as varchar(100)
--start cursor for check employee
DECLARE rohit_cursor cursor
for select empcode, emp_name from master_employee
OPEN rohit_cursor
/* first fetch starts the process */
FETCH rohit_cursor INTO @empCode ,@emp_name
WHILE @@fetch_status = 0 /* while there's still records to process */
BEGIN
print @emp_name
FETCH rohit_cursor INTO @empCode ,@emp_name
end
close rohit_cursor
DEALLOCATE rohit_cursor
--end this cursor
end --end store procedure