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_commandto the value'CANCEL'. - Then, assign a message to the
gv_messagevariable by matching the value of thegv_commandwith'SAVE'and'CANCEL'. Sincegv_messagevalue equals the value'CANCEL', thegv_messageis assigned to'Are you sure that you want to cancel?'. - Finally, output the value of the
gv_messageto the screen.
In this example, we omitted the when others branch.
Summary
- Use the
casestatement to control which code blocks to execute based on the value of an expression.