COBOL by Example: SQL (Embedded)
Embedding SQL statements in COBOL with EXEC SQL blocks, accessing relational databases like DB2, using host variables with colon prefix for data binding, checking SQLCODE for error handling, and integrating database queries into business logic.
Code
IDENTIFICATION DIVISION.
PROGRAM-ID. SQL-DEMO.
DATA DIVISION.
WORKING-STORAGE SECTION.
EXEC SQL INCLUDE SQLCA END-EXEC.
EXEC SQL BEGIN DECLARE SECTION END-EXEC.
01 EMP-ID PIC 9(5).
01 EMP-NAME PIC X(20).
EXEC SQL END DECLARE SECTION END-EXEC.
PROCEDURE DIVISION.
MOVE 1001 TO EMP-ID.
EXEC SQL
SELECT NAME INTO :EMP-NAME
FROM EMPLOYEES
WHERE ID = :EMP-ID
END-EXEC.
IF SQLCODE = 0
DISPLAY "Employee: " EMP-NAME
ELSE
DISPLAY "Error: " SQLCODE
END-IF.
STOP RUN.Explanation
Enterprise COBOL is frequently used with relational databases like DB2. This is achieved using Embedded SQL. SQL statements are placed directly in the COBOL source code, sandwiched between EXEC SQL and END-EXEC delimiters. This allows COBOL to leverage the power of SQL for complex data queries.
A precompiler translates these SQL blocks into standard COBOL calls to the database interface module. Host variables (COBOL variables used in SQL) are prefixed with a colon (e.g., :EMP-NAME) to distinguish them from SQL column names. This binding allows data to flow seamlessly between the application and the database.
Error handling in embedded SQL is managed via the SQLCA (SQL Communication Area), specifically the SQLCODE variable. A value of 0 indicates success, 100 usually means "Row Not Found", and negative values indicate errors. Checking SQLCODE after every execution is mandatory for robust database applications.

