DB2 Read Only Cursor
DB2 Read Only Cursor Example
Scenario1 - Declare the cursor for retrieving all employee names from the employee_details table.
EXEC SQL DECLARE E1 CURSOR FOR SELECT EMP_NAME FROM EMPLOYEE_DETAILS END-EXEC.
Scenario2 - Declare the read-only cursor for retrieving all employee names from the employee_details table.
EXEC SQL DECLARE E2 CURSOR FOR SELECT EMP_NAME FROM EMPLOYEE_DETAILS FOR FETCH ONLY END-EXEC.
Scenario3 - Declare the read-only cursor for retrieving all employee names from highest salary to lowest.
EXEC SQL DECLARE E2 CURSOR FOR SELECT EMP_NAME FROM EMPLOYEE_DETAILS ORDER BY SALARY DESC FOR FETCH ONLY END-EXEC.
Scenario4 -Declare the read-only cursor for retrieving the sum of salaries at the designation level.
EXEC SQL DECLARE E2 CURSOR FOR SELECT DESIGNATION, SUM(SALARY) SALARIES_TOTAL FROM EMPLOYEE_DETAILS GROUP BY DESIGNATION FOR FETCH ONLY END-EXEC.
Scenario5 - Declare the read-only cursor for retrieving the sum of salaries > 18000 at designation level.
EXEC SQL DECLARE E2 CURSOR FOR SELECT DESIGNATION, SUM(SALARY) SALARIES_TOTAL FROM EMPLOYEE_DETAILS GROUP BY DESIGNATION HAVING SUM(SALARY) > 18000 FOR FETCH ONLY END-EXEC.
Practical Example -
Scenario - The below example describes how the read-only cursor is coded in the COBOL + DB2 program.
Requirement - Display employee_details table data.
----+----1----+----2----+----3----+----4----+----5----+
IDENTIFICATION DIVISION.
PROGRAM-ID. CREADONL.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
EXEC SQL
INCLUDE SQLCA
END-EXEC.
EXEC SQL
INCLUDE EMPLDET
END-EXEC.
* DECLARING READONLY CURSOR
EXEC SQL
DECLARE CSR1 CURSOR FOR
SELECT EMP_ID,
EMP_NAME,
DESIGNATION,
MANAGER_ID,
DATE_OF_HIRE,
SALARY,
DEPT_ID
FROM EMPLOYEE_DETAILS
FOR FETCH ONLY
END-EXEC.
PROCEDURE DIVISION.
* OPENING CURSOR
EXEC SQL
OPEN CSR1
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 CSR1
END-EXEC.
STOP RUN.
FETCH-EMP-DETAILS.
* FETCH CURSOR
EXEC SQL
FETCH CSR1
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 -