Read VSAM File in REVERSE Order

Apart from reading forward, VSAM KSDS file can be read Backwards starting from a specified Key value. READPREV command is used for this purpose. To read a record in reverse order starting from a key needs to establish a starting point first which can be done using STARTBR, then READNEXT and READPREV does the backwards reading.
READPREV can be used immediately after the STARTBR, but in this case specified key using STARTBR should exist in the file otherwise it gives error. So to avoid these kind of errors, it is always recommended to use read next command before the read prev.

Steps:
Establish the Starting point

EXEC CICS STARTBR
     DATASET(WW-DATESET)
     RIDFLD(KEYFLD)
     GTEQ
     RESP(WW-RESPONSE)
END-EXEC

Issue Read Next

EXEC CICS READNEXT
     DATASET(WW-DATESET)
     INTO(WW-DATA)
     LENGTH(DATA-LGTH)
     RIDFLD(KEYFLD)
     KEYLENGTH(KEY-LGTH)
     RESP(WW-RESPONSE)
END-EXEC

Issue Read Prev

EXEC CICS READPREV
     DATASET(WW-DATESET)
     INTO(WW-DATA)
     LENGTH(DATA-LGTH)
     RIDFLD(KEYFLD)
     KEYLENGTH(KEY-LGTH)
     RESP(WW-RESPONSE)
END-EXEC

Go on Issuing the read previous commands until all the required daata is processed or EOF.

End Browse

EXEC CICS ENDBR
     DATASET(WW-DATESET)
     RESP(WW-RESPONSE)
END-EXEC.

How to Read a VSAM file from last record to first

Generally, KSDS files are established with LOW-VALUES and HIGH-VALUES records as the first and last records of the file respectively.In this case we cab easily do the reverse order reading of the file.

  • Simply MOVE HIGH-VALUES to the RIDFLD.
  • Do a Start Browse first. Then issue a READPREV which reads the HIGH-VALUES record.
  • Issue another READPREV which actually reads the last record of the file. From that record on wards continue reading the file in reverse order.

Add a Comment

Your email address will not be published. Required fields are marked *