Showing posts with label READ NEXT. Show all posts
Showing posts with label READ NEXT. Show all posts

Tuesday, 12 August 2014

COBOL READ Statement: Sequential, Random & Dynamic Examples

READ CUSTOMER-FILE AT END ... END-READ retrieves the next logical record or runs the end-of-file branch. The file must already be open for INPUT or I-O, and the program must not use the record area after an unsuccessful read.

COBOL READ statement flow from OPEN through READ and FILE STATUS to record processing
A READ retrieves one logical record, sets FILE STATUS, and selects the success or error path.

What the COBOL READ statement requires

The file name in a READ names an FD, not a record layout. Its SELECT entry defines the organization and access mode, while the FD defines the record area. Before the first read, issue OPEN INPUT when the program only reads the file or OPEN I-O when it can also update records.

SELECT CUSTOMER-FILE ASSIGN TO CUSTIN ORGANIZATION IS SEQUENTIAL ACCESS MODE IS SEQUENTIAL FILE STATUS IS WS-FILE-STATUS. FD CUSTOMER-FILE. 01 CUSTOMER-RECORD. 05 CUST-ID PIC 9(8). 05 CUST-NAME PIC X(30).

The COBOL file operations guide covers the wider OPEN, READ, WRITE, REWRITE, and CLOSE lifecycle. This page concentrates on READ syntax and the branches a program must handle.

READ syntax by access pattern

Access patternTypical formCondition to handle
Sequential fileREAD file [INTO target] AT END ... END-READAT END or status 10
Indexed file, random accessREAD file [INTO target] KEY IS key-name INVALID KEY ... END-READINVALID KEY, commonly status 23 when a record is not found
Indexed file, dynamic accessREAD file NEXT RECORD [INTO target] AT END ... END-READAT END after positioning for sequential retrieval
Relative file, random accessSet the relative key, then READ file ... INVALID KEY ... END-READINVALID KEY; the READ does not use a KEY IS phrase

NEXT is optional for a sequential file because sequential retrieval is already implied. It is required when a file opened with dynamic access is to retrieve the next record rather than perform a random read.

Sequential READ with an EOF loop

A safe loop initializes its own EOF switch, lets AT END set that switch, and processes the record only under NOT AT END.

MOVE 'N' TO WS-EOF OPEN INPUT CUSTOMER-FILE PERFORM UNTIL WS-EOF = 'Y' READ CUSTOMER-FILE AT END MOVE 'Y' TO WS-EOF NOT AT END PERFORM PROCESS-CUSTOMER END-READ END-PERFORM CLOSE CUSTOMER-FILE

When no next record exists, COBOL sets the file status before it runs the AT END statements. IBM also documents the record area as undefined after an unsuccessful READ. Keeping record processing inside NOT AT END prevents stale or unpredictable data from entering the next calculation.

QSAM warning: do not refer to the file's record area after a failed read. Depending on the access method and runtime state, doing so can cause a protection exception rather than merely return the previous record.

For a longer example that reads and writes sequential records, see COBOL sequential file organization.

How READ INTO works

The INTO phrase adds an implicit move after a successful read. COBOL first makes the current record available in the file's record area and then moves it to the receiving item. If the read fails, that move does not occur.

READ CUSTOMER-FILE INTO WS-CUSTOMER AT END MOVE 'Y' TO WS-EOF NOT AT END PERFORM VALIDATE-CUSTOMER END-READ
Choose one ownership rule: process the FD record area directly, or use READ INTO and process the working-storage copy. Mixing the two without a reason makes record changes harder to follow.

Random READ for an indexed file

Random access to an indexed file compares the key of reference with the indexed key. Move the requested value to that key before issuing the read. If no matching record exists, COBOL runs the INVALID KEY branch and sets FILE STATUS.

MOVE WS-REQUESTED-ID TO CUST-ID READ CUSTOMER-FILE INTO WS-CUSTOMER KEY IS CUST-ID INVALID KEY DISPLAY 'CUSTOMER NOT FOUND, STATUS=' WS-FILE-STATUS NOT INVALID KEY PERFORM SHOW-CUSTOMER END-READ

An indexed file can define alternate record keys, so the selected key must match a key named for that file. The COBOL indexed-file guide covers primary keys, alternate keys, and duplicate-key rules.

Dynamic access: START and READ NEXT

Dynamic access allows random and sequential operations in the same run. A common pattern uses START to establish a position and then READ NEXT RECORD to walk forward in key sequence.

MOVE WS-LOW-CUST-ID TO CUST-ID START CUSTOMER-FILE KEY IS NOT LESS THAN CUST-ID INVALID KEY MOVE 'Y' TO WS-EOF END-START PERFORM UNTIL WS-EOF = 'Y' READ CUSTOMER-FILE NEXT RECORD AT END MOVE 'Y' TO WS-EOF NOT AT END PERFORM PROCESS-CUSTOMER END-READ END-PERFORM

The sequence after START follows the key of reference. If an alternate key established the position, subsequent sequential reads use that key order until another operation changes the reference. See the COBOL START statement for its comparison conditions and positioning rules.

Random READ for a relative file

A relative file uses the data item named by the RELATIVE KEY clause. Set that relative record number before a random read. Unlike an indexed random read, the relative-file READ does not specify a KEY IS phrase.

MOVE 125 TO WS-RELATIVE-KEY READ ORDER-FILE INTO WS-ORDER INVALID KEY DISPLAY 'RELATIVE RECORD NOT FOUND, STATUS=' WS-ORDER-STATUS NOT INVALID KEY PERFORM PROCESS-ORDER END-READ

The COBOL relative organization guide explains relative keys and record-number access in more detail.

FILE STATUS values to check after READ

A FILE STATUS data item is updated after every input/output operation. Declaratives and runtime settings can affect handling, but these common two-character values are a useful starting point.

StatusMeaning in a READ pathTypical response
00Successful completionProcess the record.
04Successful read with a record-length condition under applicable rulesCheck the FD, LRECL, record format, and compiler/runtime setting.
10No next logical record; end of fileEnd the sequential loop.
23Record not found or no record at the requested keyHandle the missing indexed or relative record.
47READ attempted when the file is not open for INPUT or I-OCorrect the OPEN mode and control flow.

Use the COBOL file status code reference when the status is not one of these common READ outcomes.

Which OPEN modes permit READ?

OPEN modeCan READ?Purpose
INPUTYesRead existing records without updating them.
I-OYesRead existing records and permit supported update operations.
OUTPUTNoCreate or replace output content.
EXTENDNoAdd records at the end of a supported sequential file.

Common READ mistakes

  • Processing after AT END: the record area is undefined after an unsuccessful read.
  • Omitting NEXT under dynamic access: a sequential retrieval from a dynamically accessed file needs NEXT RECORD.
  • Using KEY IS for a relative file: set the declared relative-key item instead.
  • Ignoring FILE STATUS: INVALID KEY and AT END handle branches, while the status supplies the diagnostic value.
  • Reading after OPEN OUTPUT: READ is allowed only after OPEN INPUT or OPEN I-O.
  • Assuming READ INTO bypasses the FD area: a successful read still makes the current record available in the file's record area before the implicit move.

Official IBM references

Frequently asked questions

What does the COBOL READ statement do?

READ retrieves one logical record from an open file. Sequential access gets the next record; random access gets the record identified by a key or relative record number.

What is the difference between READ and READ NEXT?

READ gets the next record automatically in sequential access mode. In dynamic access mode, READ with NEXT RECORD requests sequential retrieval from the current file position.

When should a COBOL program use AT END?

Use AT END for a sequential read when no next logical record exists. Do not process the record area after that unsuccessful read.

What does READ INTO do in COBOL?

READ INTO retrieves a record and then performs an implicit MOVE to the receiving data item. The move occurs only when the READ succeeds.

Working rule: after every READ, follow the success, AT END, or INVALID KEY path before touching the returned record.

Monday, 28 July 2014

COBOL Indexed File Organization: RECORD KEY and READ Examples

A customer inquiry screen usually cannot read a file from the first record until it finds account 000417. The program needs to place a key value in a field, issue a keyed read, and get the matching record. That is the job of COBOL indexed file organization.

COBOL indexed file organization diagram showing a program using RECORD KEY to read a VSAM KSDS record
Key lookup plus ordered reads.

What is a COBOL indexed file?

An indexed file stores records with one or more key fields inside the record. The prime key identifies the record, and the index gives COBOL a logical path to the data. On z/OS, this is commonly coded for a VSAM key-sequenced data set, or KSDS.

IBM documents indexed organization as a file type where each record has embedded keys and each key is associated with an index. The prime key must be unique, and COBOL uses the RECORD KEY clause in FILE-CONTROL to name that field.

When indexed organization fits

Use an indexed file when the program needs direct lookup by key and also needs to process records in key order. A batch job can read the file from the lowest customer number to the highest, while an online or inquiry-style program can read one customer directly by account number.

Need Indexed file fit
Read one employee by employee number Good fit because the prime key points to one record.
Print all accounts in account number order Good fit because sequential access follows key order.
Read by department as a second path Possible with an alternate record key when the file design supports it.
Read every record once with no key lookup A plain sequential file may be simpler.

FILE-CONTROL for an indexed file

The indexed file definition belongs in the FILE-CONTROL paragraph. The important parts are ORGANIZATION IS INDEXED, an access mode, a RECORD KEY, and a file status field.

ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT CUSTOMER-FILE
        ASSIGN TO CUSTKSDS
        ORGANIZATION IS INDEXED
        ACCESS MODE IS DYNAMIC
        RECORD KEY IS CUSTOMER-ID
        ALTERNATE RECORD KEY IS CUSTOMER-ZIP
            WITH DUPLICATES
        FILE STATUS IS WS-CUST-STATUS.

ACCESS MODE IS DYNAMIC lets the program switch between keyed lookup and ordered reading. Use RANDOM when the program only reads by key. Use SEQUENTIAL when the program only walks the file in key order.

Record layout example

The key field named in RECORD KEY must be part of the record description. In this example, CUSTOMER-ID is the prime key. CUSTOMER-ZIP is an alternate key that can return more than one record when duplicates are allowed.

DATA DIVISION.
FILE SECTION.
FD  CUSTOMER-FILE.
01  CUSTOMER-RECORD.
    05 CUSTOMER-ID        PIC X(10).
    05 CUSTOMER-NAME      PIC X(30).
    05 CUSTOMER-ZIP       PIC X(05).
    05 CUSTOMER-BALANCE   PIC S9(7)V99 COMP-3.
    05 FILLER             PIC X(40).

Random READ by prime key

For a direct lookup, move the wanted key value into the record key field before the READ. A status of 00 means the record was found. A status of 23 commonly means the key was not found for indexed and relative files.

MOVE '0000000417' TO CUSTOMER-ID

READ CUSTOMER-FILE
    INVALID KEY
        DISPLAY 'CUSTOMER NOT FOUND: ' CUSTOMER-ID
    NOT INVALID KEY
        PERFORM DISPLAY-CUSTOMER
END-READ

START and READ NEXT

START positions the indexed file at a key. READ NEXT then reads forward from that point. This pattern is useful for range processing, such as all customers from account 000400 upward or all keys in a department sequence.

MOVE '0000000400' TO CUSTOMER-ID

START CUSTOMER-FILE
    KEY IS GREATER THAN OR EQUAL TO CUSTOMER-ID
    INVALID KEY
        MOVE 'Y' TO WS-END-OF-FILE
END-START

PERFORM UNTIL WS-END-OF-FILE = 'Y'
    READ CUSTOMER-FILE NEXT RECORD
        AT END
            MOVE 'Y' TO WS-END-OF-FILE
        NOT AT END
            PERFORM PROCESS-CUSTOMER
    END-READ
END-PERFORM

Alternate record keys

An alternate key gives the program a second path into the same indexed file. For example, the prime key may be employee number, while an alternate key may be department. IBM notes that alternate keys can be used to access records in a sequence other than the prime-key sequence.

Alternate keys can be unique or can allow duplicates. If duplicates are allowed, the program must be written to handle more than one matching record. Do not add alternate indexes casually; each insert, delete, or key-changing update has more index work to maintain.

File status checks

Indexed files need clear file status handling because a failed keyed read is not always a program failure. A missing customer record may be a normal business case, while an open error or duplicate prime key on write should usually stop the job or return a controlled error.

Status Meaning in common indexed-file logic
00 Successful operation.
02 Successful operation with a duplicate alternate key condition.
10 End-of-file during sequential reading.
22 Duplicate key on write or rewrite.
23 Record not found for a keyed operation.

Indexed vs sequential vs relative files

A sequential file is best when the program reads records in stored order and does not need direct lookup. A relative file is best when the record number itself is the access path. An indexed file is the normal COBOL choice when the business key matters.

Read COBOL Sequential File Organization and COBOL Relative Organization for the nearby file organization choices.

Common mistakes

Changing the prime key during REWRITE

The prime key identifies the record. Do not design update logic that changes the prime key inside a rewrite path. Delete and recreate only when the application design and recovery rules allow it.

Using random access for range work

Random access is right for one key. For a range, use START and READ NEXT. That keeps the program in key order and avoids repeated single-record calls when a sequential pass would be cleaner.

Ignoring alternate-key duplicates

If the alternate key allows duplicates, one key value can represent several records. Code the loop and stop condition carefully, especially for department, location, state, or date fields.

Related mainframe topics

For more COBOL file handling, read COBOL File Operation, COBOL File I/O Modes, COBOL File Status, COBOL Fixed and Variable Records, VSAM IDCAMS Program, and when to use VSAM KSDS, ESDS, RRDS, and LDS.

External references

Technical notes in this refresh were checked against IBM COBOL file organization documentation, IBM access mode rules, IBM VSAM indexed file coding, and IBM alternate key guidance.

FAQ

What is indexed file organization in COBOL?

It is a file organization where records contain key fields and an index provides the path to retrieve records by key or read them in key order.

What is RECORD KEY in COBOL?

RECORD KEY names the prime key field for an indexed file. The program uses that key field for direct access and ordered processing.

Can indexed files be read sequentially?

Yes. Indexed files can use sequential, random, or dynamic access. Sequential access reads records in key order.

When should I use START in COBOL?

Use START when the program needs to position an indexed file at a key before reading the next records in sequence.

New In-feed ads