Cursor (databases) - Usage

Usage

To use cursors in SQL procedures, you need to do the following:

  1. Declare a cursor that defines a result set.
  2. Open the cursor to establish the result set.
  3. Fetch the data into local variables as needed from the cursor, one row at a time.
  4. Close the cursor when done.

To work with cursors you must use the following SQL statements

This section introduces the ways the SQL:2003 standard defines how to use cursors in applications in embedded SQL. Not all application bindings for relational database systems adhere to that standard, and some (such as CLI or JDBC) use a different interface.

A programmer makes a cursor known to the DBMS by using a DECLARE ... CURSOR statement and assigning the cursor a (compulsory) name:

DECLARE cursor_name CURSOR FOR SELECT ... FROM ...

Before code can access the data, it must open the cursor with the OPEN statement. Directly following a successful opening, the cursor is positioned before the first row in the result set.

OPEN cursor_name

Programs position cursors on a specific row in the result set with the FETCH statement. A fetch operation transfers the data of the row into the application.

FETCH cursor_name INTO ...

Once an application has processed all available rows or the fetch operation is to be positioned on a non-existing row (compare scrollable cursors below), the DBMS returns a SQLSTATE '02000' (usually accompanied by an SQLCODE +100) to indicate the end of the result set.

The final step involves closing the cursor using the CLOSE statement:

CLOSE cursor_name

After closing a cursor, a program can open it again, which implies that the DBMS re-evaluates the same query or a different query and builds a new result set.

Read more about this topic:  Cursor (databases)

Famous quotes containing the word usage:

    ...Often the accurate answer to a usage question begins, “It depends.” And what it depends on most often is where you are, who you are, who your listeners or readers are, and what your purpose in speaking or writing is.
    Kenneth G. Wilson (b. 1923)

    Pythagoras, Locke, Socrates—but pages
    Might be filled up, as vainly as before,
    With the sad usage of all sorts of sages,
    Who in his life-time, each was deemed a bore!
    The loftiest minds outrun their tardy ages.
    George Gordon Noel Byron (1788–1824)

    I am using it [the word ‘perceive’] here in such a way that to say of an object that it is perceived does not entail saying that it exists in any sense at all. And this is a perfectly correct and familiar usage of the word.
    —A.J. (Alfred Jules)