Home >> FAQs/Tutorials >> SQL Server FAQ

SQL Server FAQ - "DECLARE ... CURSOR" - Declaring Cursor Objects

By: FYIcenter.com

(Continued from previous topic...)

How To Declare a Cursor with "DECLARE ... CURSOR"?

If you want to use a cursor to represent the result set of a query, you need to define a cursor name with a SELECT sub-statement using the "DECLARE ... CURSOR" statement using the following syntax format:

DECLARE cursor_name CURSOR FOR
  SELECT ...; 

Note that the DECLARE statement will not actually execute the SELECT sub-statement. It only attaches the SELECT sub-statement to the cursor.

A cursor name should be deallocated to free up server resources if the cursor is not needed any more.

The tutorial example below shows you how to declare and deallocate a cursor.

USE FyiCenterData;
GO

DECLARE fyi_cursor CURSOR FOR
  SELECT * FROM fyi_links;
-- other statements
DEALLOCATE fyi_cursor;
GO

(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...