CASE statement is used for creating a control structure which contains several conditional execution of a statement depending on search conditions. CASE statement will be ended with END CASE statement. Its faster method than using several IF .. ELSE conditions.
Inside the CASE statement WHEN statement is used for specifying the search criteria and ELSE statement for handling the situation when the search not found. Instead of ELSE statement we can also use WHEN OTHERS to handle the same situation. CASE statement can be used in two different ways, watch the difference by the following sample CASE statement.
CASE
WHEN month = 1 THEN toMONTH = ‘Jan’;
WHEN month = 2 THEN toMONTH = Feb’;
WHEN month = 3 THEN toMONTH = ‘Mar’;
WHEN month = 4 THEN toMONTH = ‘Apr’;
WHEN month = 5 THEN toMONTH = ‘May’;
WHEN month = 6 THEN toMONTH = ‘Jun’;
WHEN month = 7 THEN toMONTH = ‘Jul’;
WHEN month = 8 THEN toMONTH = ‘Aug’;
WHEN month = 9 THEN toMONTH = ‘Sep’;
WHEN month = 10 THEN toMONTH = ‘Oct’;
WHEN month = 11 THEN toMONTH = ‘Nov’;
WHEN month = 12 THEN toMONTH = ‘Dec’;
ELSE toMONTH = ‘Not a valid Month’;
(Or WHEN OTHERS toMONTH = ‘Not a valid Month’)
END CASE
The same program can be written as following also
CASE month
WHEN 1 THEN toMONTH = ‘Jan’;
WHEN 2 THEN toMONTH = Feb’;
WHEN 3 THEN toMONTH = ‘Mar’;
WHEN 4 THEN toMONTH = ‘Apr’;
WHEN 5 THEN toMONTH = ‘May’;
WHEN 6 THEN toMONTH = ‘Jun’;
WHEN 7 THEN toMONTH = ‘Jul’;
WHEN 8 THEN toMONTH = ‘Aug’;
WHEN 9 THEN toMONTH = ‘Sep’;
WHEN 10 THEN toMONTH = ‘Oct’;
WHEN 11 THEN toMONTH = ‘Nov’;
WHEN 12 THEN toMONTH = ‘Dec’;
ELSE toMONTH = ‘Not a valid Month’;
(Or WHEN OTHERS toMONTH = ‘Not a valid Month’)
END CASE
Here we can see that the variable name month is specified with CASE statement and can avoid using it with WHEN statement. But in some cases it wont be suitable, if we are checking with different variables and values and need to execute various WHEN statements
If all the WHEN statements failed to match the criteria, then “ELSE” or “WHEN OTHERS” statements will be executed. In that time if those statements were not present inside our CASE block, then runtime error -28901 is returned.
Also Read : View Other ABAP Keywords & Syntax -> ABAP Transaction codes