Switch Expression

Description:

A SWITCH conditional expression uses case distinctions to produce a result based on the specified operand. It either returns a value of the declared type or raises a class-based exception if no match is found.

  • The type can be:
    • A non-generic data type (e.g., i, string, or a data element).
    • The # symbol.

Syntax:

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

Example:

"Switch
DATA: lt_products TYPE TABLE OF string,
      lv_status   TYPE string.

APPEND 'P001' TO lt_products.
APPEND 'P002' TO lt_products.
APPEND 'P003' TO lt_products.

LOOP AT lt_products INTO DATA(lv_product).
  lv_status = SWITCH #( lv_product
    WHEN 'P001' THEN 'In Stock'
    WHEN 'P002' THEN 'Low Stock'
    WHEN 'P003' THEN 'Out of Stock'
    ELSE 'Unknown Product'
  ).
  WRITE: / |Product { lv_product } is { lv_status }|.
ENDLOOP.

Thanks for visiting!

Sangeeta Singh

Leave a Reply

Discover more from HANAxABAP

Subscribe now to keep reading and get access to the full archive.

Continue reading