BudiBadu Logo
Samplebadu

COBOL by Example: Indexed Files

COBOL 2002

Working with indexed files for random access by primary key, implementing ORGANIZATION IS INDEXED with RECORD KEY, using ACCESS MODE RANDOM or DYNAMIC, handling INVALID KEY errors, and understanding VSAM KSDS datasets on mainframes.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. INDEXED-FILES.
       
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT EMP-FILE ASSIGN TO "emp.dat"
           ORGANIZATION IS INDEXED
           ACCESS MODE IS RANDOM
           RECORD KEY IS EMP-ID.
           
       DATA DIVISION.
       FILE SECTION.
       FD  EMP-FILE.
       01  EMP-REC.
           05 EMP-ID   PIC 99.
           05 EMP-NAME PIC X(10).
           
       PROCEDURE DIVISION.
           OPEN INPUT EMP-FILE.
           MOVE 15 TO EMP-ID.
           READ EMP-FILE
               INVALID KEY DISPLAY "Record 15 not found"
               NOT INVALID KEY DISPLAY "Found: " EMP-NAME
           END-READ.
           CLOSE EMP-FILE.
           STOP RUN.

Explanation

Indexed files allow you to access records directly using a primary key, without reading all preceding records. This is critical for database-like performance. You must specify ORGANIZATION IS INDEXED and define a RECORD KEY which must be a field within the file record.

With ACCESS MODE IS RANDOM, you can set the key value and issue a READ command to fetch that specific record. The INVALID KEY clause handles cases where the record doesn't exist. You can also use ACCESS MODE IS DYNAMIC to mix sequential and random access.

On mainframes, these are typically VSAM KSDS (Key Sequenced Data Sets). They are the backbone of many legacy transaction processing systems, allowing for rapid retrieval of customer data, account balances, and inventory items.

Code Breakdown

7
ORGANIZATION IS INDEXED. Tells the system this is not a flat text file but has an index structure (like ISAM or VSAM).
8
ACCESS MODE IS RANDOM. We intend to jump to specific records rather than reading from start to finish.
9
RECORD KEY IS EMP-ID. Defines the field within the record that acts as the unique identifier.
20
MOVE 15 TO EMP-ID. Prepares the key we want to search for. The system looks at this variable to know which record to fetch.
22
INVALID KEY. Executes if no record with ID 15 exists in the file.
23
NOT INVALID KEY. Executes if the record WAS found. This is a cleaner way to handle success than using a separate flag.