SEARCH ALL with a key PIC XX

101 Views Asked by At

I'm using SERACH ALL on a table with a key with a type PIC X(02)

Bellow is my table declaration

01  WS-VAL    PIC X(02). 
01  WS-TABLE.
        03  WS-TABLE-LINE OCCURS 400 TIMES
                                 ASCENDING KEY IS TAB-KEY
                                 INDEXED BY IND-TAB.
            05  TAB-KEY      PIC X(02).
            05  TAB-LIB      PIC X(15).

Bellow how i use SEARCH ALL

SET IND-TAB     TO 1
SEARCH ALL WS-TABLE-LINE
   AT END 
      DISPLAY 'NOT FOUND'
   WHEN TAB-KEY (IND-TAB) = VAL
      DISPLAY 'FOUND'
END-SEARCH

VAL exists on the keys of the table but the message 'NOT FOUND' is usually displayed

1

There are 1 best solutions below

1
Simon Sobisch On

You're use of SEARCH is nearly correct (set the index on plain SEARCH as this operates from the current index value, but not on SEARCH ALL which sets the index itself), but the table likely isn't.

SEARCH ALL goes over the complete table with a binary search. We don't know so we have to guess:

  • you have much less than 400 entries in, possibly even less than 200
  • the data is not initialized, so contains either garbage or low-value (common on mainframes) or spaces (common on PC, would also be the case on mainframe after INITIALIZE WS-TABLE)

Then your SEARCH will start at around entry 201, finds a key that is less than what you search for, therefore goes up to 301, still finds a key that is less, then goes to 351, 375, ... and ends at position 400 with only keys seen that are less than your current one.

The dirty way is to ensure that all keys are pre-set for example with HIGH-VALUE.
The right way is to add something like DEPENDING ON WS-TAB-ENTRIES to your OCCURS clause and set this correct; in this case the search only happens binary in the range of the current setup maximum, not the absolute maximum any more.

Note: as SEARCH ALL does a binary lookup, the data in the table must be sorted per your definition - if this isn't the case then do a SORT WS-TABLE once (again: after setting the OCCURS DEPENDING ON value or pre-set all keys to HIGH-VALUE (or ZZZ if you like that more) - otherwise the "empty" entries will be sorted up front [that alone would make your SEARCH ALL work correctly, but waste computing power]).