Variable-length Tables


  • A variable-length table has no predefined size, and size will be decided during the runtime.
  • Variable-length tables use the OCCURS DEPENDING ON clause with a variable that is used to decide the table size during the runtime.

Syntax -

01 table-name.
   02 variable  [PIC data-type(length1)] 
                OCCURS integer1 [TO integer2] TIMES
                [DEPENDING ON data-name]
			    [DESCENDING|ASCENDING KEY IS key-var]
                [INDEXED BY index-name]
Note! All statements coded in [ ] are optional.

Parameters -

  • table-name - specifies the table name.
  • variable - specifies the data item name.
  • integer1 - The number of times the data item should be repeated.
  • integer1 [TO integer2] - integer1 is minimum number of times and integer2 to maximum number of times. TO is applicable when DEPENDING ON is coded.
  • DEPENDING ON data-name - This makes the table variable-length, with its size determined by the current value of data-name.
  • DESCENDING|ASCENDING KEY IS key-var - Specifies the array sorting order using key-var.
  • INDEXED BY index-name - This defines an index for the table. The index can be used to reference specific occurrences within the table.

Practical Example -


Scenario - Variable length table declaration, usage, and displaying items in it.

Code -

----+----1----+----2----+----3----+----4----+----5----+
       ...
       WORKING-STORAGE SECTION.
       01 WS-STUDENT-CNT        PIC 9(02).
       01 WS-CLASS.
          03 WS-STUDENT  OCCURS 1 TO 5 TIMES
                         DEPENDING ON WS-STUDENT-CNT.
             05 WS-ROLL-NO      PIC 9(03) VALUE 1.
             05 WS-NAME         PIC X(10) VALUE 'STUDENT'.
       ...
       PROCEDURE DIVISION.
           ACCEPT WS-STUDENT-CNT.
           DISPLAY "CLASS INFO: " WS-CLASS.
           ...

Run JCL -

//MATEPKRJ JOB MSGLEVEL=(1,1),NOTIFY=&SYSUID
//*
//STEP01  EXEC PGM=TBOCCURS
//STEPLIB  DD  DSN=MATEPK.COBOL.LOADLIB,DISP=SHR
//SYSOUT   DD  SYSOUT=*
//SYSIN    DD  *
03
/*

Output -

CLASS INFO: 001STUDENT   001STUDENT   001STUDENT