Module 9: DB2 COBOL Programming
EXEC SQL
EXEC SQL is the marker that tells the DB2 precompiler "an SQL statement starts here". Every SQL statement inside a COBOL program - SELECT, INSERT, UPDATE, DELETE, OPEN, FETCH, CLOSE, COMMIT - is wrapped in EXEC SQL ... END-EXEC.
The EXEC SQL ... END-EXEC format
- Syntax: EXEC SQL sql-statement END-EXEC. The period after END-EXEC belongs to the COBOL sentence.
- EXEC SQL and END-EXEC are COBOL words as far as the precompiler is concerned; the SQL between them follows DB2 SQL syntax.
- The precompiler strips the SQL out, puts it in the DBRM, and leaves a CALL to the DB2 language interface in the modified source.
- There is also EXEC SQL INCLUDE ... END-EXEC, which pulls in a copybook (SQLCA or a DCLGEN member) at precompile time.
SQL statements you can code with EXEC SQL
- Data retrieval: SELECT ... INTO (single row), DECLARE CURSOR, OPEN, FETCH, CLOSE (multiple rows).
- Data change: INSERT, UPDATE, DELETE - including positioned UPDATE/DELETE with WHERE CURRENT OF cursor-name.
- Transaction control: COMMIT (save changes) and ROLLBACK (undo changes).
- Others: INCLUDE, WHENEVER (error handling directive), and dynamic SQL statements like PREPARE and EXECUTE.
INCLUDE variants
- EXEC SQL INCLUDE SQLCA END-EXEC brings in the SQL communication area, which holds SQLCODE after every statement.
- EXEC SQL INCLUDE member-name END-EXEC brings in a DCLGEN-generated copybook with table declaration and matching host variables.
- INCLUDE is processed at precompile time, like a COPY, not at COBOL compile time.
Example of the common EXEC SQL statements in one program:-
EXEC SQL
SELECT MAX(SALARY)
INTO :WS-MAX-SAL
FROM EMP
WHERE DEPTNO = :WS-DEPT
END-EXEC.
EXEC SQL
INSERT INTO EMP (EMPNO, EMPNAME, DEPTNO, SALARY)
VALUES (:WS-EMPNO, :WS-EMPNAME, :WS-DEPT, :WS-SALARY)
END-EXEC.
EXEC SQL
UPDATE EMP
SET SALARY = SALARY * 1.10
WHERE DEPTNO = :WS-DEPT
END-EXEC.
EXEC SQL
DELETE FROM EMP
WHERE EMPNO = :WS-EMPNO
END-EXEC.
EXEC SQL COMMIT END-EXEC.
