Friday, September 4, 2009

The SEARCH Statement

The SEARCH Statement
Syntax
Format 1
SEARCH identifier-1 [ VARYING { identifier-2
index-name-1 }]
[AT END imperative-statement-1]
{ WHEN condition-1 { imperative-statement-2
NEXT SENTENCE }} ...
[END-SEARCH]
Format 2
SEARCH ALL identifier-3
[AT END imperative-statement-3]
WHEN { identifier-3 { IS EQUAL TO
IS = } { identifier-4
literal-1
arithmetic-expression-1 } }
condition-name-1
[ AND { identifier-5 { IS EQUAL TO
IS = } { identifier-6
literal-2
arithmetic-expression-2 } }]
condition-name-2
{ imperative-statement-4
NEXT SENTENCE }}
[END-SEARCH]

Description
The SEARCH statement is used to locate items in tables. Format 1 performs a serial search and format 2 performs a binary search
Identifier-1 must be defined with an OCCURS clause including the INDEXED BY phrase. Identifier-3 must be defined with an OCCURS clause including the INDEXED BY and ASCENDING or DESCENDING KEY phrases.
When the statement is executed, each of the entries in the table named after SEARCH is used to resolve the conditions in each of the WHEN clauses in turn. When a match is found the index associated with the table is set to the entry number of the matching item and the statement(s) following the WHEN clause and before the next WHEN clause, are executed and control is then transferred to the statement following the END-SEARCH. If no matching WHEN clause is found in the entire table, the code following the AT END statement is executed.

Tips
1. When implementing a serial search, to insure that the entire table is searched, use the SET statement to initialize the index associated with the table to 1 before coding the SEARCH statement..
2. Due to the overhead required to implement a binary search, it is recommended that a serial search be used for tables with less than 100 entries.
3. If the table to be searched contains more elements than are actually in use, define the table with the OCCURS DEPENDING ON phrase to avoid including the unused table elements in the SEARCH process.