ABAP case

Summary: in this tutorial, you will learn how to use the ABAP case statement.

Introduction to ABAP case Statement

The case statement defines a control structure that contains multiple code blocks. It executes no more than one code block by matching an operand with a list of values.

The following shows the syntax of the case statement:

case operand.
   when expression_1. 
     [code_block_1]
   when expression_2. 
     [code_block_2]
   ...
   when expression_n. 
     [code_block_n]
   when others.
     [code_block_other]
endcase.

In this syntax, the operand is compared with the expression_1, expression_2, … from the top down.

If the first match is found, the corresponding code block is executed. In case no match found, the code_block_other in the when others branch is executed.

The when others branch is optional. If you omit it and there is no match, the processing continues after endcase.

ABAP case statement examples

The following example illustrates how to use the case statement:

data gv_command type string value 'CANCEL'.
data gv_message type string.

case gv_command.
  when 'SAVE'.
    gv_message = 'The document has been saved successfully.'.
  when 'CANCEL'.
    gv_message = 'Are you sure that you want to cancel?'.
endcase.

write gv_message.

How it works.

  • First, declare two variables and initialize the gv_command to the value 'CANCEL'.
  • Then, assign a message to the gv_message variable by matching the value of the gv_command with 'SAVE' and 'CANCEL'. Since gv_message value equals the value 'CANCEL', the gv_message is assigned to 'Are you sure that you want to cancel?'.
  • Finally, output the value of the gv_message to the screen.

In this example, we omitted the when others branch.

Summary

  • Use the case statement to control which code blocks to execute based on the value of an expression.