Search Example


Scenario - Let us assume we have a employee table for an organization with all active employee numbers (unsorted) and we are trying to searching for exmployee E0004 existance. If the employee found, we should display "Employee found". Otherwise, display "Employee not found".

----+----1----+----2----+----3----+----4----+----5----+
       IDENTIFICATION DIVISION.
       PROGRAM-ID. TBSEARCH.
       AUTHOR. MTH.
	   
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-ORG.
          03 WS-EMPLOYEE OCCURS 6 TIMES 
                         INDEXED BY IDX-EMP.   
             05 WS-EMPLOYEE-NUM       PIC X(05).   

       PROCEDURE DIVISION.
      * Initializing table with active employee details
      * every 5 characters represents one employee number.
           MOVE 'E0005E0002E0004E0001E0007'
  		     TO WS-ORG.
      * Initializing index
           SET IDX-EMP         TO 1.
      * Search table using index
           SEARCH WS-EMPLOYEE VARYING IDX-EMP 
               AT END DISPLAY "Employee not found"
             WHEN WS-EMPLOYEE-NUM(IDX-EMP) = 'E0004'
                  DISPLAY "Employee found"
           END-SEARCH.

           STOP RUN.

Output -

Employee found

Explaining Example -

In the above example:

  • It defines a table named WS-ORG with an OCCURS clause to hold employee numbers.
  • It initializes this table with active employee details represented as five-character strings, where each string represents one employee number.
  • It initializes the index and then searches the table sequentially using the SEARCH statement, varying the index.
  • The employee number 'E0004' is found in the table, it displays "Employee found".