Menu
CoddyTech

SORT USING GIVING

Part of the Files and Reports section of Coddy's COBOL Programming journey. Lesson 15 of 22.

SORT puts the records of a file in order of one or more keys. It works through a sort file, declared with SD instead of FD:

    SELECT WORK-FILE ASSIGN TO SORTWK.
SD WORK-FILE.
01 WORK-REC.
    05 W-REGION PIC X(5).

The sort file's SELECT needs only a name: GnuCOBOL keeps the work data set for itself.

USING names the file to read and GIVING the file to write. SORT opens and closes both itself, so the program does not:

SORT WORK-FILE
    ON ASCENDING KEY W-REP
    USING SALES-FILE
    GIVING SORTED-FILE.

Keys come in order of importance. The second key orders records whose first key is equal:

ON ASCENDING KEY W-REGION
ON DESCENDING KEY W-AMT
challenge icon

Challenge

Easy

Sort SALES-FILE into SORTED-FILE through WORK-FILE, by W-AMT with the biggest amount first. The first line is WEST Raj   00500.

Try it yourself

       IDENTIFICATION DIVISION.
       PROGRAM-ID. SORTAMT.
       ENVIRONMENT DIVISION.
       INPUT-OUTPUT SECTION.
       FILE-CONTROL.
           SELECT SALES-FILE ASSIGN TO SALESIN
               ORGANIZATION IS LINE SEQUENTIAL.
           SELECT SORTED-FILE ASSIGN TO DISPLAY
               ORGANIZATION IS LINE SEQUENTIAL.
           SELECT WORK-FILE ASSIGN TO SORTWK.
       DATA DIVISION.
       FILE SECTION.
       FD SALES-FILE.
       01 SALES-REC.
           05 S-REGION PIC X(5).
           05 S-REP PIC X(6).
           05 S-AMT PIC 9(5).
       FD SORTED-FILE.
       01 SORTED-REC PIC X(16).
       SD WORK-FILE.
       01 WORK-REC.
           05 W-REGION PIC X(5).
           05 W-REP PIC X(6).
           05 W-AMT PIC 9(5).
       PROCEDURE DIVISION.
           *> Write your code here
           STOP RUN.

All lessons in Files and Reports