Skip to content
systemcoding.dev
Mainframe

Embed a SELECT INTO with EXEC SQL in COBOL

Read one Db2 row into COBOL host variables with EXEC SQL SELECT INTO, then branch on SQLCODE, in Enterprise COBOL 6.4 with Db2 13 for z/OS.

1 min read
Summarize in AI

A single-row lookup in COBOL is a SELECT ... INTO wrapped in EXEC SQL ... END-EXEC. Each column lands in a host variable that you write with a leading colon, and the statement must return at most one row.

cobol
EXEC SQL
  SELECT LASTNAME, SALARY
    INTO :EMP-LASTNAME, :EMP-SALARY
    FROM EMPLOYEE
   WHERE EMPNO = :EMP-EMPNO
END-EXEC.
EVALUATE SQLCODE
  WHEN 0    DISPLAY 'FOUND ' EMP-LASTNAME
  WHEN +100 DISPLAY 'NO SUCH EMPLOYEE'
  WHEN -811 DISPLAY 'MORE THAN ONE ROW'
  WHEN OTHER DISPLAY 'SQL ERROR ' SQLCODE
END-EVALUATE.
Text
FOUND HAAS

SQLCODE 0 means one row was returned. +100 means no row matched, and -811 means the predicate matched several rows, which is a program error rather than a data condition. Db2 13 for z/OS and Enterprise COBOL 6.4 both behave this way.

The -811 case is the one that surprises people, because the same statement works in test data and fails in production. If you only want any one match, add FETCH FIRST 1 ROW ONLY to the select, or use a cursor when you need every row.

Taggedcoboldb2
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.