How to read a VSAM file sequentially from first to last entry or vice versa

Document ID : KB000054774
Last Modified Date : 14/02/2018
Show Technical Document Details

Description:

It may be necessary to read a complete file sequentially from the first to the last entry or vice versa. Here you find an example of doing this with low effort using NCL.

Solution:

NCL provides access to VSAM-Clusters by using &FILE verbs.

It may be necessary to read a complete file sequentially from the first to the last entry or vice versa. An easy way to get the first (or the last) entry of a File is by using parameter OPT=FWD (or OPT=BWD) in the first &FILE GET statement. The key of that &FILE GET is stored in &FILEKEY. In the loop you read the next entry by using OPT=FWD (or OPT=BWD) again without referencing a key value! The loop is controlled by the Feedback provided into variable &FILEKEY. As long as this value is 0, a record from the file could be read. When trying to read after the last record was read, &FILEKEY contains 4 and the loop ends.

Note: You will only get the first record of a file using OPT=FWD if there was no prior &FILE GET to that file.

The following example shows how a complete file is read in ascending order. The fields of the file are read into variables &1, &2, etc as ARGS is used:

========================================================================================
-*---------------------------------------*
-* Reading a file in ascending order     *
-*---------------------------------------*
&FILE GET DD=<ddname> OPT=FWD ARGS
&DOWHILE &FILERC = 0
  ...
  processing of read record
  ...
  &FILE GET DD=<ddname> OPT=FWD ARGS
&DOEND
 ========================================================================================

The complete file can be read in descending order, too. Two small changes in the above example will fulfill that:

  • Change OPT=FWD to OPT=BWD in both &FILE GET statements:
========================================================================================
-*---------------------------------------*
-* Reading a file in descending order    *
-*---------------------------------------*
&FILE GET DD=<ddname> OPT=BWD ARGS
&DOWHILE &FILERC = 0
  ...
  processing of read record
  ...
  &FILE GET DD=<ddname> OPT=BWD ARGS
&DOEND
========================================================================================