Compaq COBOL AAQ2G1FTK User Manual

Page 284

Advertising
background image

Using the SORT and MERGE Statements
9.1 Sorting Data with the SORT Statement

Example 9–2 USING Phrase Replaces INPUT PROCEDURE Phrase

.
.
.
PROCEDURE DIVISION.
000-SORT SECTION.
010-DO-THE-SORT.

SORT SORT-FILE ON ASCENDING KEY SORT-KEY-1

ON DESCENDING KEY SORT-KEY-2
USING INPUT-FILE
OUTPUT PROCEDURE IS 200-WRITE-OUTPUT

THRU 230-DONE-OUTPUT.

DISPLAY "END OF SORT".
STOP RUN.

200-WRITE-OUTPUT SECTION.
210-OPEN-OUTPUT.

OPEN OUTPUT OUTPUT-FILE.

220-GET-SORTED-RECORDS.

RETURN SORT-FILE AT END

CLOSE OUTPUT-FILE
GO TO 230-DONE-OUTPUT.

MOVE SORT-RECORD TO OUTPUT-RECORD.
WRITE OUTPUT-RECORD.
GO TO 220-GET-SORTED-RECORDS.

230-DONE-OUTPUT SECTION.
240-EXIT-OUTPUT.

EXIT.

9.1.5 Maintaining the Input Order of Records Using the WITH DUPLICATES IN

ORDER Phrase

The sort orders data in the sequence specified in the ASCENDING KEY and
DESCENDING KEY phrases. However, records with duplicate sort keys may not
be written to the output file in the same sequence as they were read into it. The
WITH DUPLICATES IN ORDER phrase ensures that any records with duplicate
sort keys are in the same order in the output file as in the input file.

The following list shows the potential difference between sorting with the WITH
DUPLICATES IN ORDER phrase and sorting without it:

Input File

Sorted Without
Duplicates in Order

Sorted With
Duplicates in Order

Record

Record

Record

Name

Data

Name

Data

Name

Data

JONES ABCD

DAVIS LMNO

DAVIS LMNO

DAVIS LMNO

JONES EFGH

JONES ABCD

WHITE STUV

JONES ABCD

JONES EFGH

JONES EFGH

SMITH 1234

SMITH 1234

SMITH 1234

WHITE STUV

WHITE STUV

WHITE WXYZ

WHITE WXYZ

WHITE WXYZ

If you omit the WITH DUPLICATES IN ORDER phrase, you cannot predict
the order of records with duplicate sort keys. For example, the JONES records
might not be in the same sequence as they were in the input file, but the WHITE
records might be in the same order as in the input file.

9–6 Using the SORT and MERGE Statements

Advertising