Friday, September 4, 2009

The READ Statement

The READ Statement
Syntax
Format 1
READ file-name-1 [ NEXT
PREVIOUS ] RECORD [{| WITH [NO] LOCK
INTO identifier-1 |}]
[AT END imperative-statement-1]
[NOT AT END imperative-statement-2]
[END-READ]

Format 2
READ file-name-1 RECORD [{| WITH [NO] LOCK
INTO identifier-1 |}] [KEY IS {data-name-1}]
[INVALID KEY imperative-statement-1]
[NOT INVALID KEY imperative-statement-2]
[END-READ]
Description
The READ statement is used to acquire a record from a file. The record read is loaded into the 01 (record description) following the FD (file description) associated with the file. If the INTO phrase is included, the record read will also be copied into the INTO data item. WITH LOCK requests that the record be locked (no access by other users or processes allowed), if the file's open included locking. WITH NO LOCK reads the record without locking it. The two different formats are used for two different types of reads and each is described in the correspondingly numbered item below.
1. The first format performs a sequential read of the file. If the last operation performed on a file was an OPEN, the first record of the file is read. If the previous operation was a READ, the next sequential record in the file is read. If the end of file is reached as a result of the read, no record is returned and the code between AT END and NOT AT END, if any, will be executed. If the end of the file is not reached, the code between NOT AT END and END-READ, if any, will be executed.
2. The second format performs a random read of the file. The record matching the current value of the file key, if any, will be read. If the file has multiple keys, the desired key is specified in the KEY IS clause. If the file as multiple keys and the KEY IS clause is omitted, the file's primary key will be used. If no matching record exists, no record is returned and the code between INVALID KEY and NOT INVALID KEY, if any, will be executed. If the a matching record is found, the code between NOT INVALID KEY and END-READ, if any, will be executed.

Tips
1. If there is a file status associated with the file, it will be set after the READ is executed to indicate the result of the READ. A value of "00" means successful, "10" means the end of file was encountered for the sequential READ, and "23" means there was no matching record for the key supplied for the random READ.
2. Any file mentioned must be the subject of a SELECT statement and a file description (FD). Files must be open for input or input/output prior to executing the READ statement.
3. When used in a program with a SORT statement, the sort file itself can never be read.
4. When using the random read, be sure the value of the record you wish to access has been loaded into the key before executing the READ statement.