sapdev logo background
sapdev logo sapdev logo
Comments

SAP CONDITIONAL EXPRESSION SWITCH documentation, setup help and example usage



Return to SAP documentation index


ARTICLE

SWITCH - Conditional Operator

Syntax
... SWITCH type( operand
WHEN const1 THEN result1
[ WHEN const2 THEN result2 ]
...
[ ELSE resultn ] ) ...

Effect
A conditional expression with the conditional operator SWITCH has a result, result , that is specified by a case distinction. Either a value with the data type specified by type is produced or a class-based exception raised. The same applies to type as to a conditional expression with COND .
The first position operand in the parenthesis is the value checked in the case distinction. It is a general expression position . It must be followed by at least one WHEN . Literals and constants can be specified for const behind WHEN . It must be possible to compare
them with operand . This can be followed by any number of
WHEN s with further constant values. An ELSE can be specified at the end. This expression compares the values of the operand
operand with the specified constant values, one by one, and chooses the result behind
THEN for which the values of operand and constant are identical for the first time. The selected
result determines the result of the conditional expression. If no matches are found, the result
specified after ELSE is selected. If ELSE is not specified, the result is the initial value of the data type type .
If an item specified after THEN or ELSE can be selected, either the result is set or a class-based exception is raised, just as with a conditional expression
COND .

Notes
  • Text symbols for const cannot be specified after WHEN .

  • A conditional expression with SWITCH has the same meaning as the following conditional expression with COND :

  • COND type( WHEN operand = const1 THEN result1
    [ WHEN operand = const2 THEN result2 ]
    ...
    [ ELSE resultn ] )

    Example
    Conditional operator SWITCH in an operand position in a loop. The loop is exited when the exception after ELSE is caught.
    CLASS cx_overflow DEFINITION INHERITING FROM cx_static_check.
    ENDCLASS.

    DATA(out) = cl_demo_output=>new( ).
    DO.
    TRY.
    out->write(
    SWITCH string( sy-index
    WHEN 1 THEN 'one'
    WHEN 2 THEN 'two'
    WHEN 3 THEN 'three'
    ELSE THROW cx_overflow( ) ) ).
    CATCH cx_overflow.
    out->display( ).
    EXIT.
    ENDTRY.
    ENDDO.
    Documentation extract taken from SAP system, � Copyright SAP AG. All rights reserved




    CONDITIONAL_EXPRESSION_RESULT
    CONDITIONAL_OPERATOR_GLOSRY




    comments powered by Disqus