Chapter 7. Embedded SQL 99
The SQL FETCH statement is the equivalent to all CHAIN, READ, READE, READP, and
READPE operations in RPG. By using a scrollable cursor, it is also possible to move the
cursor forwards and backwards in your result table.
CLOSE statement to close the cursor for use within the program.
7.8.1 The DECLARE statement
The declare statement is used to define the cursor name and the associated SELECT
statement.
An example of the DECLARE statement is shown below, which is important for embedded
static SQL. All parts written in parenthesis can be omitted. For more information look at
iSeries DB2 Universal Database for iSeries SQL Reference.
DECLARE Cursor Name (DYNAMIC (SCROLL)) CURSOR (WITH HOLD)
FOR Select Statement
(FOR READ ONLY/FOR FETCH ONLY)
(FOR UPDATE (OF Column1, Column2,.....ColumnN))
(OPTIMIZE FOR n ROWS)
(WITH Isolation Level)
Cursor name
Any name can be specified for the cursor, but a cursor name must be unique in the source
member where it is defined.
NO SCROLL or (DYNAMIC) SCROLL
This specifies whether the cursor is scrollable or not scrollable. If neither NO SCROLL nor
SCROLL is specified a serial cursor is defined.
– NO SCROLL
Specifies that a serial cursor is defined.
In Example 7-23 a serial cursor is declared by omitting the SCROLL or NO SCROLL
keyword.
Example 7-23 Declaring a serial cursor
C/EXEC SQL
C+ Declare CsrOrdH Cursor for
C+ Select Customer_Number, sum(Order_Total)
C+ from Order_Header
C+ where Order_Number between :FirstOrderNo and :LastOrderNo
C+ and Year(Order_Date) = :PrevYear
C+ group by Customer_Number
Note: Contrary to RPG, more than one row can be received in one FETCH statement,
by using host structure arrays. The next FETCH will receive the next or previous block
or rows.
Note: When using a serial cursor, an OPEN without a preceding CLOSE will not
reposition the cursor on the top of the result table. To be sure that the cursor is really
closed, execute a CLOSE statement before your OPEN statement.
Note: Even if the source member contains several independent procedures, the cursor
name must be unique.