Cursors and prepared statements

 

Cursors and prepared statements are scoped to the compilation unit and also to the connection.

Scoping to the compilation unit means that a program called from another separately compiled program cannot use a cursor or prepared statement that was opened or prepared by the calling program. Scoping to the connection means that each connection within a program can have its own separate instance of a cursor or prepared statement.

The following distributed unit of work example shows how the same cursor name is opened in two different connections, resulting in two instances of cursor C1. Figure 1. Example of cursors in a DUW program

    .....
     EXEC SQL DECLARE C1 CURSOR FOR
                 SELECT * FROM CORPDATA.EMPLOYEE;
     /* Connect to local and open C1 */
     EXEC SQL CONNECT TO LOCALSYS;
     EXEC SQL OPEN C1;
     /* Connect to the remote system and open C1 */
     EXEC SQL CONNECT TO SYSA;
     EXEC SQL OPEN C1;
     /* Keep processing until done */
     while (NOT_DONE) {
        /* Fetch a row of data from the local system */
        EXEC SQL SET CONNECTION LOCALSYS;
        EXEC SQL FETCH C1 INTO :local_emp_struct;
        /* Fetch a row of data from the remote system */
        EXEC SQL SET CONNECTION SYSA;
        EXEC SQL FETCH C1 INTO :rmt_emp_struct;
        /* Process the data */
        .....
     }
     /* Close the cursor on the remote system */
     EXEC SQL CLOSE C1;
     /* Close the cursor on the local system */
     EXEC SQL SET CONNECTION LOCALSYS;
     EXEC SQL CLOSE C1;
     .....

 

Parent topic:

Distributed unit of work