DB2 · 2026-10-11

DB2 Cursor Basics for COBOL Programs

Learn how DB2 cursors work in COBOL programs and when to use DECLARE, OPEN, FETCH, and CLOSE.

A DB2 cursor allows a COBOL program to process multiple rows returned by a SQL query. Without a cursor, a program typically retrieves one row at a time using a singleton SELECT. With a cursor, the program can read a result set row by row.

When to use a cursor

Use a cursor when the query can return more than one row. Examples:

Cursor lifecycle

A cursor follows a simple lifecycle:

1. DECLARE CURSOR
2. OPEN CURSOR
3. FETCH rows until no more rows
4. CLOSE CURSOR

Example structure:

EXEC SQL
    DECLARE C1 CURSOR FOR
    SELECT CUSTOMER_ID, CUSTOMER_NAME
      FROM CUSTOMER
     WHERE STATUS = 'A'
END-EXEC.

EXEC SQL OPEN C1 END-EXEC.

PERFORM UNTIL SQLCODE = 100
EXEC SQL
FETCH C1 INTO :WS-CUST-ID, :WS-CUST-NAME
END-EXEC
IF SQLCODE = 0
PERFORM PROCESS-CUSTOMER
END-IF
END-PERFORM.

EXEC SQL CLOSE C1 END-EXEC.
```

SQLCODE handling

Important SQLCODE values:

Production programs should handle negative SQLCODE values carefully and display enough context for debugging.

Cursor performance

Cursor performance depends on access path, predicates, indexes, and number of rows fetched. A cursor that reads millions of rows may still be correct, but it must be designed with batch runtime in mind.

Good practices:

Conclusion

DB2 cursors are a practical bridge between SQL result sets and COBOL record-style processing. Understanding cursor lifecycle and SQLCODE handling is essential for mainframe development and production support.

← Back to all articles