DB2 Unit 11
DB2 Unit 11
Page 1 of 9
18 Cursor Processing
Objectives - Student will
Understand how a cursor is used Be able to process multiple rows using cursor verbs
Page 2 of 9
18 Cursor Processing
Is a pointer that identifies the current row in a results table Used when multiple rows might be returned to the result table Can work through a result table much like reading through a standard sequential file A program may have more than one cursor
Page 3 of 9
18 Cursor Processing
Step 1 - DECLARE CURSOR
Defines the result table to DB2 but does not create the result table
18 Cursor Processing
Step 2 - OPEN cursor_name
Generates the results table specified by the DECLARE
Page 5 of 9
18 Cursor Processing
Step 3 - FETCH
Advances the cursor one row in the results table
EXEC SQL FETCH cursor_name INTO :host-variable1,:host-variable2,,,, END-EXEC. IF SQLCODE = +100 END-OF-CURSOR............
DB2_Tr Ver. 1.0.0 04/12/1998 Page 6 of 9
18 Cursor Processing
Step 4 - CLOSE
Releases the results table associated with the cursor Releases resources
Page 7 of 9
18 Cursor Processing
UPDATE Using a Cursor
EXEC SQL DECLARE cursor_name CURSOR SELECT FOR
FOR UPDATE OF column1, column2, column3 END-EXEC. EXEC SQL UPDATE table_name SET column1 = :column1 WHERE CURRENT OF cursor_name DB2_Tr Ver. 1.0.0 04/12/1998 END-EXEC. Page 8 of 9
18 Cursor Processing
DELETE Using a CURSOR
EXEC SQL DECLARE cursor_name CURSOR SELECT FOR
FROM table_name WHERE END-EXEC. EXEC SQL DELETE FROM table_name WHERE CURRENT OF cursor_name END-EXEC. predicate
Page 9 of 9