Microsoft Docs

SQL Server Docs

Synopsis

Retrieves rows from the result set associated with an open cursor.

FETCH [ NEXT | PRIOR | FIRST | LAST | ABSOLUTE | RELATIVE ] 
    [ FROM | IN ] cursor_name
    [ INTO @variable_name [ ,...n ] ]

Parameters

ArgumentDescription
NEXTMoves the cursor forward to the next row (default).
PRIORMoves the cursor backward to the previous row.
FIRSTMoves the cursor to the first row of the result set.
LASTMoves the cursor to the last row of the result set.
ABSOLUTE nMoves the cursor to the nth row. A positive number counts from the start; a negative number counts from the end.
RELATIVE nMoves the cursor n rows forward (or backward if negative) from its current position.
FROM | INSpecifies the name of the cursor.
INTO @variableStores the column values of the fetched row into the listed variables.

Remarks

The FETCH statement must be used only after a cursor has been declared and opened. If the fetch operation cannot find a row, the variables specified in the INTO clause are set to NULL, and the @@FETCH_STATUS function returns a non‑zero value.

Examples

Fetching rows sequentially

DECLARE @id int, @name nvarchar(50);
DECLARE employee_cursor CURSOR FOR
SELECT EmployeeID, FirstName FROM dbo.Employees ORDER BY EmployeeID;

OPEN employee_cursor;
FETCH NEXT FROM employee_cursor INTO @id, @name;
WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT CAST(@id AS varchar(10)) + ': ' + @name;
    FETCH NEXT FROM employee_cursor INTO @id, @name;
END;
CLOSE employee_cursor;
DEALLOCATE employee_cursor;

Fetching an absolute row

DECLARE @id int, @name nvarchar(50);
DECLARE emp CURSOR FOR SELECT EmployeeID, FirstName FROM dbo.Employees;

OPEN emp;
FETCH ABSOLUTE 5 FROM emp INTO @id, @name;
PRINT 'Fifth employee: ' + CAST(@id AS varchar) + ' - ' + @name;
CLOSE emp;
DEALLOCATE emp;

Related Topics