COBOL by Example: VSAM Basics
Accessing VSAM (Virtual Storage Access Method) files on IBM mainframes, using ORGANIZATION IS INDEXED with dynamic access mode, implementing robust FILE STATUS error handling for production code, and working with Key Sequenced Data Sets for high-performance storage.
Code
IDENTIFICATION DIVISION.
PROGRAM-ID. VSAM-DEMO.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT CUST-FILE ASSIGN TO "CUST.DAT"
ORGANIZATION IS INDEXED
ACCESS MODE IS DYNAMIC
RECORD KEY IS CUST-KEY
FILE STATUS IS WS-STATUS.
DATA DIVISION.
FILE SECTION.
FD CUST-FILE.
01 CUST-REC.
05 CUST-KEY PIC 9(5).
05 CUST-DATA PIC X(50).
WORKING-STORAGE SECTION.
01 WS-STATUS PIC 99.
PROCEDURE DIVISION.
OPEN I-O CUST-FILE.
IF WS-STATUS NOT = "00"
DISPLAY "VSAM Open Error: " WS-STATUS
STOP RUN.
*> Read a specific record
MOVE 12345 TO CUST-KEY.
READ CUST-FILE
INVALID KEY DISPLAY "Record not found"
END-READ.
CLOSE CUST-FILE.
STOP RUN.Explanation
VSAM (Virtual Storage Access Method) is a high-performance file storage access method used on IBM mainframes. It is the backbone of legacy data processing, allowing for efficient storage and retrieval of vast amounts of data. While the COBOL syntax looks similar to standard Indexed Files, the underlying mechanism is different and highly optimized, often using Key Sequenced Data Sets (KSDS).
In this example, we use ACCESS MODE IS DYNAMIC, which allows the program to switch between sequential access (reading next record) and random access (reading by key) on the fly. This is a common requirement for browsing data or processing transactions where you might need to find a specific customer and then print a report of their subsequent transactions.
Robust error handling is critical when working with VSAM. The FILE STATUS clause is mandatory for production code. It captures the result of every I/O operation, allowing the program to react to conditions like "Record Locked," "Duplicate Key," or "File Full" (Status 34, 22, and 30 respectively), ensuring data integrity is maintained.

