There are two types of expressions used in CASE
statements: simple and searched. These expressions correspond to the type of
CASE statement in which they are used. See .
A simple CASE
expression selects a result from one or more
alternatives, and returns the result. Although it contains a block that might
stretch over several lines, it really is an expression that forms part of a
larger statement, such as an assignment or a procedure call. The CASE
expression uses a selector,
an expression whose value determines which alternative to return.
A CASE
expression has the form illustrated in . The selector (grade
) is followed
by one or more WHEN
clauses, which are checked sequentially. The
value of the selector determines which clause is evaluated. The first WHEN
clause that matches the value of the selector determines the
result value, and subsequent WHEN
clauses are not evaluated. If
there are no matches, then the optional ELSE
clause is
performed.
Example 2-26 Using the WHEN Clause With a CASE
Statement
The optional ELSE
clause works similarly to theELSE
clause in an IF
statement. If the value of the
selector is not one of the choices covered by a WHEN
clause, theELSE
clause is executed. If no ELSE
clause is provided
and none of the WHEN
clauses are matched, the expression returnsNULL
.
A searched CASE
expression lets you test different conditions
instead of comparing a single expression to various values. It has the form
shown in .
A searched CASE
expression has no selector. EachWHEN
clause contains a search condition that yields aBOOLEAN
value, so you can test different variables or multiple
conditions in a single WHEN
clause.
Example 2-27 Using a Search Condition With a CASE
Statement
The search conditions are evaluated sequentially. The BOOLEAN
value of each search condition determines which WHEN
clause is
executed. If a search condition yields TRUE
, its WHEN
clause is executed. After any WHEN
clause is executed, subsequent
search conditions are not evaluated. If none of the search conditions yieldsTRUE
, the optional ELSE
clause is executed. If noWHEN
clause is executed and no ELSE
clause is
supplied, the value of the expression is NULL
.