CASE

The CASE instruction specifies statement blocks that must be executed conditionally.

Syntax 1

CASE expression-1
  WHEN expression-2
    { statement | EXIT CASE }
    [...]
  [ OTHERWISE 
    { statement | EXIT CASE }
    [...]
  ] 
END CASE

Syntax 2

CASE
  WHEN boolean-expression
    { statement | EXIT CASE }
    [...]
  [ OTHERWISE 
    { statement | EXIT CASE }
    [...]
  ] 
END CASE
  1. expression-1 is any expression supported by the language.
  2. expression-2 is an expression that is tested against expression-1.
  3. expression-1 and expression-2 should have the same data type.
  4. boolean-expression is any boolean expression supported by the language.
  5. statement is any instruction supported by the language.

Usage

In a CASE flow control block, the first matching WHEN block is executed. If there is no matching WHEN block, then the OTHERWISE block is executed. If there is no matching WHEN block and no OTHERWISE block, the program execution continues with the next statement following the END CASE keyword.

The EXIT CASE statement transfers the program control to the statement following the END CASE keyword. There is an implicit EXIT CASE statement at the end of each WHEN block and at the end of the OTHERWISE block. The OTHERWISE block must be the last block of the CASE instruction.

A null expression is considered as false: When doing a CASE expr ... WHEN [NOT] NULL using the syntax 1, it always evaluates to FALSE. Use syntax 2 as CASE ... WHEN expr IS NULL to test if an expression is null.

Make sure that expression-2 is not a boolean expression when using the first syntax. The compiler will not raise an error in this case, but you might get unexpected results at runtime.

If there is more than one expression-2 matching expression-1 (syntax 1), or if two boolean expressions (syntax 2) are true, only the first matching WHEN block will be executed.

MAIN
   DEFINE v CHAR(10)
   LET v = "C1"
   -- CASE Syntax 1
   CASE v 
     WHEN "C1"
       DISPLAY "Value is C1"
     WHEN "C2"
       DISPLAY "Value is C2"
     WHEN "C3"
       DISPLAY "Value is C3"
     OTHERWISE
       DISPLAY "Unexpected value"
   END CASE
   -- CASE Syntax 2
   CASE
     WHEN ( v="C1" OR v="C2" )
       DISPLAY "Value is either C1 or C2"
     WHEN ( v="C3" OR v="C4" )
       DISPLAY "Value is either C3 or C4"
     OTHERWISE
       DISPLAY "Unexpected value"
   END CASE
END MAIN