Host Programs, DECLARE, OPEN, CLOSE CURSOR (Part 1 of 3)
The DECLARE CURSOR statement consists of a cursor name and the SELECT statement that will create the results. The SELECT statement is identical in format to the SQL SELECT statements discussed earlier. In the following examples, we shall use the prefix EXEC SQL and the terminator END-EXEC.
The syntax is:
EXEC SQL
DECLARE cursor_name [CURSOR FOR]
SELECT column1, column2 ...
FROM table_name ...
WHERE ...
[FOR UPDATE OF column1, column2 ...]
END-EXEC
A typical declare cursor using the VENDOR_TBL would look something like this:
EXEC SQL
DECLARE VENDOR_CSR
SELECT VENDOR_NAME, STATE
FROM VENDOR_TBL
WHERE COUNTRY = :SEARCH-COUNTRY
END-EXEC
The cursor is named VENDOR_CSR and points, one at a time, to each selected row in the table. SQL knows by the colon that :SEARCH-COUNTRY is the host variable that is defined in the host program (without the colon).
The DECLARE CURSOR statement may be placed anywhere in the host program as long as it occurs after any host variable definitions and before any statements that reference the cursor.