Menu
CoddyTech

READ by Key

Part of the Programs That Work Together section of Coddy's COBOL Programming journey. Lesson 9 of 16.

With random access, a program reads a record by its key: it moves the key into the key field, then reads.

MOVE 10002 TO CUST-ID
READ CUST-MAST

INVALID KEY runs when no record has that key, and NOT INVALID KEY when the record was found:

READ CUST-MAST
    INVALID KEY DISPLAY "No customer"
    NOT INVALID KEY DISPLAY CUST-NAME
END-READ

The file status tells the same story: 00 found, 23 no record with that key. A program can leave out INVALID KEY and test the status instead.

With neither INVALID KEY nor a FILE STATUS, a missing key stops the program. After a failed read the record area holds no new record, so never use its fields.

challenge icon

Challenge

Easy

CALL "LOADMAST" builds CUSTMAST from CUSTIN, and DO-KEY runs for each id in KEYSIN, moving it to CUST-ID. Read that record: print CUST-NAME and SHOW-BAL, or No customer and the id when there is none.

Try it yourself

       IDENTIFICATION DIVISION.
       PROGRAM-ID. LOOKUP.
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT KEY-FILE ASSIGN TO KEYSIN
               ORGANIZATION IS LINE SEQUENTIAL.
           SELECT CUST-MAST ASSIGN TO CUSTMAST
               ORGANIZATION IS INDEXED
               ACCESS MODE IS RANDOM
               RECORD KEY IS CUST-ID
               FILE STATUS IS MAST-STATUS.
       DATA DIVISION.
       FILE SECTION.
       FD KEY-FILE.
       01 KEY-REC.
           05 KEY-ID         PIC 9(5).
       FD CUST-MAST.
           COPY CUSTREC.
       WORKING-STORAGE SECTION.
       01 MAST-STATUS    PIC XX.
       01 EOF-FLAG       PIC X VALUE "N".
           88 END-OF-FILE  VALUE "Y".
       01 SHOW-BAL       PIC ZZ,ZZ9.99.
       PROCEDURE DIVISION.
       MAIN-LOGIC.
           CALL "LOADMAST"
           OPEN INPUT KEY-FILE
           OPEN INPUT CUST-MAST
           PERFORM UNTIL END-OF-FILE
               READ KEY-FILE
                   AT END SET END-OF-FILE TO TRUE
                   NOT AT END PERFORM DO-KEY
               END-READ
           END-PERFORM
           CLOSE KEY-FILE CUST-MAST
           STOP RUN.
       DO-KEY.
           MOVE KEY-ID TO CUST-ID
           *> Read the customer here
           CONTINUE.

All lessons in Programs That Work Together