DB2 Scrollable Cursor Example
Input -
Cursor Declaration-
EXEC SQL DECLARE CSS1 SCROLL CURSOR FOR SELECT EMP_NAME, MANAGER_ID FROM EMPLOYEE_DETAILS FOR FETCH ONLY END-EXEC.
Scenario1 - Place the cursor on the next row of the result table from the current position.
EXEC SQL FETCH NEXT FROM CSS1 END-EXEC.
Scenario2 - Place the cursor on the previous row of the result table from the current position.
EXEC SQL FETCH PRIOR FROM CSS1 END-EXEC.
Scenario3 - Position the cursor on the first row of the result table.
EXEC SQL FETCH FIRST FROM CSS1 END-EXEC.
Scenario4 - Position the cursor on the last row of the result table.
EXEC SQL FETCH LAST FROM CSS1 END-EXEC.
Scenario5 - Position the cursor before the first row of the result table.
EXEC SQL FETCH BEFORE FROM CSS1 END-EXEC.
Scenario6 - Position the cursor after the last row of the result table.
EXEC SQL FETCH AFTER FROM CSS1 END-EXEC.
Scenario7 - Position the cursor 3 rows before the current cursor position.
EXEC SQL FETCH RELATIVE -3 FROM CSS1 END-EXEC.
Scenario8 - Position the cursor 4 rows after the current cursor position.
EXEC SQL FETCH RELATIVE +4 FROM CSS1 END-EXEC.
Pratical Example
Scenario - The below example describes how the scrollable cursor is coded in the COBOL + DB2 program.
Requirement - Display employee_details table data and from row 3 again.
SCROLLABLE CURSOR Example Code -
----+----1----+----2----+----3----+----4----+----5----+
IDENTIFICATION DIVISION.
PROGRAM-ID. CSCROLL.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
EXEC SQL
INCLUDE SQLCA
END-EXEC.
EXEC SQL
INCLUDE EMPLDET
END-EXEC.
* DECLARING SCROLLABLE CURSOR
EXEC SQL
DECLARE CSR_SCROLL SCROLL CURSOR FOR
SELECT EMP_ID,
EMP_NAME,
DESIGNATION,
MANAGER_ID,
DATE_OF_HIRE,
SALARY,
DEPT_ID
FROM EMPLOYEE_DETAILS
ORDER BY EMP_ID
FOR FETCH ONLY
END-EXEC.
PROCEDURE DIVISION.
* OPENING CURSOR
EXEC SQL
OPEN CSR_SCROLL
END-EXEC.
* FETCHING CURSOR LOOP UNTIL END OF RESULT TABLE
IF SQLCODE EQUAL ZERO
PERFORM FETCH-EMP-DETAILS
THRU FETCH-EMP-DETAILS-EXIT
UNTIL SQLCODE NOT EQUAL 0
END-IF.
* POSITION THE CURSOR ON THE FIRST ROW OF RESULT TABLE
EXEC SQL
FETCH FIRST FROM CSR_SCROLL
END-EXEC.
* POSITION THE CURSOR ON THE THIRD ROW OF RESULT TABLE
EXEC SQL
FETCH RELATIVE +1 FROM CSR_SCROLL
END-EXEC.
* FETCHING CURSOR LOOP UNTIL END OF RESULT TABLE
IF SQLCODE EQUAL ZERO
PERFORM FETCH-EMP-DETAILS
THRU FETCH-EMP-DETAILS-EXIT
UNTIL SQLCODE NOT EQUAL 0
END-IF.
* CLOSING CURSOR
EXEC SQL
CLOSE CSR_SCROLL
END-EXEC.
STOP RUN.
FETCH-EMP-DETAILS.
* FETCH CURSOR
EXEC SQL
FETCH CSR_SCROLL
INTO :EMP-ID,
:EMP-NAME,
:DESIGNATION,
:MANAGER-ID
:MANAGER-ID-NI,
:DATE-OF-HIRE,
:SALARY,
:DEPT-ID
END-EXEC.
EVALUATE SQLCODE
WHEN ZERO
DISPLAY EMP-ID, "|", EMP-NAME, "|",
DESIGNATION, "|", MANAGER-ID, "|",
DATE-OF-HIRE, "|", SALARY, "|", DEPT-ID
WHEN 100
CONTINUE
WHEN OTHER
DISPLAY "DB2 ERROR: ", SQLCODE
END-EVALUATE.
FETCH-EMP-DETAILS-EXIT.
EXIT.
Output -