T-SQL Tutorial

Fetch cursors - TSQL Tutorial


In this page you can learn how to retrieve rows from a Transact-SQL server cursor.

Fetch cursor Syntax:

FETCH
[ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE { n | @nvar }
| RELATIVE { n | @nvar }
]
FROM
{ { cursor_name } | @cursor_variable_name }
[ INTO @variable_name [ ,...n ] ] ;





Fetch in cursors example:

USE model;
GO
DECLARE Student_Cursor CURSOR FOR
  SELECT id, first_name, last_name, country
FROM dbo.students WHERE country = 'US';
OPEN Student_Cursor;
WHILE @@FETCH_STATUS = 0
   BEGIN
     FETCH NEXT FROM Student_Cursor;
   END;
CLOSE Student_Cursor;
DEALLOCATE Student_Cursor;
GO

idfirst_namelast_namecountry
1TomWHITEUS
2MichaelJONESUS
5OliviaBARNESUS