Sort Example


Scenario - Let us assume we have an employee file that contains employee information unsorted. The file should be sorted based on the employee number (1-5 characters) in ascending order.

EMPREC -

----+----1----+----2----+----3----+----4----+--
           05 EMP-NUM         PIC 9(05).
           05 FILLER          PIC X(05).
           05 EMP-NAME        PIC X(10).
           05 EMP-DESG        PIC X(09).
           05 FILLER          PIC X(01).
           05 EMP-SALARY      PIC 9(05).
           05 FILLER          PIC X(12).

Input (MATEPK.EMPFILE.NSINPUT1) -

----+----1----+----2----+----3----+----4----+--
E0004EMPLOYEE4     TL   DEPT1LOC1 0000050000
E0002EMPLOYEE2     MGR  DEPT1LOC1 0000080000
E0006EMPLOYEE6     SE   DEPT1LOC1 0000034000
E0001EMPLOYEE1     DIR       LOC1 0000100000

Code -

----+----1----+----2----+----3----+----4----+----5----+
       IDENTIFICATION DIVISION.
       PROGRAM-ID. SORTFLS.
       AUTHOR. MTH.

       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT EMPFILE1 ASSIGN TO INPUT1.
           SELECT EMPFILEO ASSIGN TO OUTPUT1.
           SELECT WORKFILE ASSIGN TO WORK1.

       DATA DIVISION. 
       FILE SECTION.
       FD EMPFILE1
           RECORD CONTAINS 47 CHARACTERS
           DATA RECORD EMP-REC1
           RECORDING MODE F.
       01 EMP-REC1.
          COPY EMPREC.
       FD EMPFILEO 
           RECORD CONTAINS 47 CHARACTERS 
           DATA RECORD EMP-RECO 
           RECORDING MODE F.
       01 EMP-RECO.
          COPY EMPREC.
       SD WORKFILE
           RECORD CONTAINS 47 CHARACTERS 
           DATA RECORD WORK-REC
           RECORDING MODE F.
       01 WORK-REC.
          05 WORK-EMP-NUM     PIC 9(05).
          05 WORK-REM-REC     PIC X(42).

       PROCEDURE DIVISION.
           SORT WORKFILE
             ON ASCENDING KEY WORK-EMP-NUM 
                USING EMPFILE1
                GIVING EMPFILEO.
           STOP RUN.

JCL -

///MATEPKRJ JOB MSGLEVEL=(1,1),NOTIFY=&SYSUID
//*
//STEP01  EXEC PGM=SORTFLS
//STEPLIB  DD  DSN=MATEPK.COBOL.LOADLIB,DISP=SHR
//INPUT1   DD  DSN=MATEPK.EMPFILE.NSINPUT1,DISP=SHR
//OUTPUT1  DD  DSN=MATEPK.EMPFILE.NSOUT1,
//            DISP=(NEW,CATLG,DELETE),
//            SPACE=(TRK,(3,2),RLSE),
//            UNIT=SYSDA,
//            DCB=(DSORG=PS,RECFM=FB,LRECL=47,BLKSIZE=470)
//WORK1    DD  DSN=&&TEMP,
//            DISP=(NEW,DELETE,DELETE),
//            SPACE=(CYL,(10,5),RLSE),
//            UNIT=SYSDA,
//            DCB=(DSORG=PS,RECFM=FB,LRECL=47,BLKSIZE=470)
//SYSOUT   DD  SYSOUT=*

Output (MATEPK.EMPFILE.NSOUT1) -

----+----1----+----2----+----3----+----4----+--
E0001EMPLOYEE1     DIR       LOC1 0000100000
E0002EMPLOYEE2     MGR  DEPT1LOC1 0000080000
E0004EMPLOYEE4     TL   DEPT1LOC1 0000050000
E0006EMPLOYEE6     SE   DEPT1LOC1 0000034000

Explaining Example -

In the above example:

  • SORT statement sorts the input file records based on the employee number (1-5 bytes) and writes into the output file.