Home >> FAQs/Tutorials >> SQL Server FAQ

SQL Server FAQ - "FETCH" - Fetching the Next Row from a Cursor

By: FYIcenter.com

(Continued from previous topic...)

How To Fetch the Next Row from a Cursor with a "FETCH" Statement?

When the result set is ready in a cursor, you can use a FETCH statement to retrieve one row from the result set in the same format as a SELECT statement. The FETCH statement has the following formats:

FETCH NEXT FROM cursor_name;
FETCH PRIOR FROM cursor_name;
FETCH FIRST FROM cursor_name;
FETCH LAST FROM cursor_name;
FETCH ABSOLUTE n FROM cursor_name;
FETCH RELATIVE n FROM cursor_name;

The tutorial exercise below shows you how FETCH statements are used to retrieve the first row and the second row back from a cursor:

USE FyiCenterData;
GO

DECLARE fyi_cursor CURSOR FOR
  SELECT * FROM fyi_links;
OPEN fyi_cursor;

FETCH NEXT FROM fyi_cursor; 
FETCH NEXT FROM fyi_cursor; 

CLOSE fyi_cursor;
DEALLOCATE fyi_cursor;
GO
id   url                notes       counts  time
---- ------------------ ----------- ------- -----
101  dev.fyicenter.com  NULL        NULL    NULL
(1 row(s) affected)

id   url                notes       counts  time
---- ------------------ ----------- ------- -----
102  dba.fyicenter.com  Nice site.  8       NULL
(1 row(s) affected)

(Continued on next topic...)

  1. What Are Cursors?
  2. How To Declare a Cursor with "DECLARE ... CURSOR"?
  3. How To Execute the Cursor Queries with "OPEN" Statements?
  4. How To Fetch the Next Row from a Cursor with a "FETCH" Statement?
  5. How To Transfer Data from a Cursor to Variables with a "FETCH" Statement?
  6. How To Loop through the Result Set with @@FETCH_STATUS?
  7. How To Declare and Use Cursor Variables?
  8. How To Create a Scrollable Cursor with the SCROLL Option?
  9. How To Create a Dynamic Cursor with the DYNAMIC Option?

Related Articles:

More...


Other Tutorials/FAQs:

More...


Related Resources:

More...


Selected Jobs:

More...