CASE Statement in ABAP — Multi-Branch Decision Control Guide
Table of Contents
- • What is a CASE Statement?
- ↳ Key Execution Rules:
- • Basic Syntax of CASE
- • Basic Example: Department ID Lookup
- ↳ Execution Output:
- • Grouping Multiple Values with OR
- ↳ Execution Output:
- • Modern ABAP 7.4+ Alternative: The SWITCH Operator
- ↳ Syntax:
- ↳ Advanced SWITCH Feature: Raising Exceptions (THEN THROW)
- • CASE TYPE OF — Object Type Inspection in ABAP Objects
- • Technical Comparison Matrix: Decision Structures in ABAP
- • Real-World Enterprise Scenario: Sales Order Status Processor
- • Frequently Asked Questions
- ↳ 1. Can you write range comparisons (e.g. WHEN > 100) inside an ABAP CASE statement?
- ↳ 2. What is the modern ABAP 7.4+ inline expression equivalent of a CASE statement?
- ↳ 3. What happens if a CASE statement has no WHEN OTHERS block and none of the WHEN clauses match the control variable?
- • Best Practices for Clean Code
- • Summary
![]()
While building custom SAP programs, you will constantly encounter business logic that needs to evaluate a variable and execute different actions based on its value.
For example, when processing a sales document in S/4HANA, the program needs to check document status (VBAK-GBSTK):
- If Status =
'A'-> Order is open. - If Status =
'B'-> Order is partially processed. - If Status =
'C'-> Order is fully completed. - If Status =
'D'-> Order is blocked for credit review.
You could write this logic using a long chain of IF-ELSEIF-ELSE statements. It will execute without error. But as the number of branches grows, your code becomes verbose, hard to read, difficult to unit test, and prone to maintenance bugs.
The CASE statement (and its modern ABAP 7.4+ sibling, the SWITCH operator) provides a clean, highly readable structure designed specifically for multi-branch value matching.
This guide covers everything about CASE in SAP ABAP: basic syntax, WHEN OTHERS fallbacks, grouping values with OR, comparison against IF-ELSEIF, modern SWITCH expressions, CASE TYPE OF object pattern matching, and real-world enterprise scenarios.
What is a CASE Statement?
The CASE statement is an ABAP control structure that evaluates a single variable or expression against a series of target values, executing the matching code block and exiting immediately.
┌────────────────────────┐
│ CASE variable │
└───────────┬────────────┘
│
┌───────────────────────┼───────────────────────┐
▼ ▼ ▼
WHEN 'A' WHEN 'B' WHEN OTHERS
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Open Order │ │ In Progress │ │ Invalid Code │
└──────────────┘ └──────────────┘ └──────────────┘
│ │ │
└───────────────────────┼───────────────────────┘
▼
EXIT (ENDCASE)
Key Execution Rules:
- Exact Evaluation: The control variable is evaluated once at the top of the
CASEstatement. - Sequential Matching: System checks each
WHENclause from top to bottom. - Immediate Exit: As soon as a matching
WHENclause evaluates to true, SAP executes that code block and jumps directly toENDCASE. SubsequentWHENclauses are ignored. - Fallback Handling: If no
WHENclause matches, control flows to the optionalWHEN OTHERSblock.
Basic Syntax of CASE
Here is the standard syntax for a CASE statement in ABAP:
CASE <variable_or_expression>.
WHEN <value_1>.
" Executed if variable equals value_1
WHEN <value_2>.
" Executed if variable equals value_2
WHEN <value_3> OR <value_4>.
" Executed if variable equals value_3 or value_4
WHEN OTHERS.
" Fallback executed if no preceding WHEN matched
ENDCASE.
Basic Example: Department ID Lookup
Let’s look at a simple program that maps department IDs to department names:
REPORT z_case_dept_demo.
DATA: lv_dept_id TYPE i VALUE 3,
lv_dept_name TYPE string.
CASE lv_dept_id.
WHEN 1.
lv_dept_name = 'Human Resources'.
WHEN 2.
lv_dept_name = 'Financial Accounting'.
WHEN 3.
lv_dept_name = 'Sales & Distribution'.
WHEN 4.
lv_dept_name = 'Information Technology'.
WHEN OTHERS.
lv_dept_name = 'Unknown Department'.
ENDCASE.
WRITE: / 'Department Name:', lv_dept_name.
Execution Output:
Department Name: Sales & Distribution
Since lv_dept_id is 3, the system matches WHEN 3, assigns 'Sales & Distribution', and skips all remaining branches.
Grouping Multiple Values with OR
When multiple input values require the exact same processing logic, you group them inside a single WHEN statement using the OR keyword. This eliminates duplicate code blocks.
REPORT z_case_vowel_check.
DATA: lv_char TYPE c VALUE 'E',
lv_type TYPE string.
CASE lv_char.
WHEN 'A' OR 'E' OR 'I' OR 'O' OR 'U'
OR 'a' OR 'e' OR 'i' OR 'o' OR 'u'.
lv_type = 'Vowel'.
WHEN '0' OR '1' OR '2' OR '3' OR '4' OR '5' OR '6' OR '7' OR '8' OR '9'.
lv_type = 'Digit'.
WHEN OTHERS.
lv_type = 'Consonant or Special Character'.
ENDCASE.
WRITE: / 'Character Type:', lv_type.
Execution Output:
Character Type: Vowel
Modern ABAP 7.4+ Alternative: The SWITCH Operator
Starting with ABAP Release 7.40, SAP introduced expression-based operators. Instead of writing 10 lines of CASE ... ENDCASE code just to assign a value to a variable, you can use the inline SWITCH operator in a single line.
Syntax:
DATA(target_var) = SWITCH #( source_var
WHEN val1 THEN res1
WHEN val2 THEN res2
WHEN val3 THEN res3
ELSE default_res
).
Advanced SWITCH Feature: Raising Exceptions (THEN THROW)
In modern ABAP OO, if a SWITCH expression encounters an unhandled value, you can throw an exception directly from inside the ELSE branch:
DATA(lv_description) = SWITCH string( p_code
WHEN 'A' THEN 'Active'
WHEN 'I' THEN 'Inactive'
ELSE THROW cx_invalid_code_exception( )
).
CASE TYPE OF — Object Type Inspection in ABAP Objects
In ABAP Object-Oriented programming, CASE TYPE OF is a specialized form of CASE used to inspect the dynamic runtime class type of an object reference variable.
INTERFACE lif_vehicle.
ENDINTERFACE.
CLASS lcl_car DEFINITION.
PUBLIC SECTION.
INTERFACES lif_vehicle.
ENDCLASS.
CLASS lcl_truck DEFINITION.
PUBLIC SECTION.
INTERFACES lif_vehicle.
ENDCLASS.
" In your processing routine:
DATA: lo_vehicle TYPE REF TO lif_vehicle.
lo_vehicle = NEW lcl_car( ).
CASE TYPE OF lo_vehicle.
WHEN TYPE lcl_car INTO DATA(lo_car).
WRITE: / 'Object is a Car instance.'.
WHEN TYPE lcl_truck INTO DATA(lo_truck).
WRITE: / 'Object is a Truck instance.'.
WHEN OTHERS.
WRITE: / 'Unknown Vehicle Type.'.
ENDCASE.
CASE TYPE OF replaces old IS INSTANCE OF checks and downcasting (?=) with clean, type-safe pattern matching.
Technical Comparison Matrix: Decision Structures in ABAP
| Feature / Metric | CASE Statement | IF / ELSEIF | SWITCH Expression | COND Expression | CASE TYPE OF |
|---|---|---|---|---|---|
| Evaluation Type | Discrete single variable | Complex boolean expressions | Single variable inline | Complex expressions inline | Runtime class instance |
Relational Check (>, <) | ❌ Not supported | ✅ Supported | ❌ Not supported | ✅ Supported | ❌ Not supported |
| Code Style | Classical multi-line | Classical multi-line | Modern ABAP 7.40+ | Modern ABAP 7.40+ | ABAP Objects |
| Kernel Optimization | $O(1)$ Jump Table | $O(N)$ Linear Search | $O(1)$ Jump Table | $O(N)$ Linear Search | RTTI Metaclass Check |
| Inline Target Assignment | Manual statement | Manual statement | DATA(...) = SWITCH | DATA(...) = COND | INTO DATA(...) |
Real-World Enterprise Scenario: Sales Order Status Processor
Let’s build a practical ABAP report demonstrating CASE and SWITCH in an S/4HANA enterprise setting.
REPORT z_sales_order_processor.
TYPES: BEGIN OF ty_order_summary,
vbeln TYPE vbeln_va,
vkorg TYPE vkorg,
netwr TYPE netwr_ak,
gbstk TYPE gbstk,
status_desc TYPE string,
action_code TYPE string,
END OF ty_order_summary.
DATA: lt_orders TYPE TABLE OF ty_order_summary.
" Read Sales Orders from S/4HANA table VBAK
SELECT vbeln, vkorg, netwr, gbstk
FROM vbak
INTO CORRESPONDING FIELDS OF TABLE @lt_orders
UP TO 10 ROWS.
IF sy-subrc <> 0.
WRITE: / 'No sales orders found.'.
RETURN.
ENDIF.
LOOP AT lt_orders ASSIGNING FIELD-SYMBOL(<ls_order>).
" 1. Traditional CASE for complex multi-statement processing
CASE <ls_order>-gbstk.
WHEN 'A'.
<ls_order>-status_desc = 'Open / Not Processed'.
<ls_order>-action_code = 'CREATE_DELIVERY'.
WHEN 'B'.
<ls_order>-status_desc = 'Partially Processed'.
<ls_order>-action_code = 'CHECK_BACKORDER'.
WHEN 'C'.
<ls_order>-status_desc = 'Completely Processed'.
<ls_order>-action_code = 'ARCHIVE'.
WHEN 'D'.
<ls_order>-status_desc = 'Credit Blocked / Review Needed'.
<ls_order>-action_code = 'NOTIFY_CREDIT_MGR'.
WHEN OTHERS.
<ls_order>-status_desc = 'Unknown Document Status'.
<ls_order>-action_code = 'MANUAL_INSPECTION'.
ENDCASE.
" Display summary
WRITE: / |Order: { <ls_order>-vbeln } |,
|Org: { <ls_order>-vkorg } |,
|Status: { <ls_order>-status_desc } |,
|Action: { <ls_order>-action_code }|.
ENDLOOP.
Frequently Asked Questions
1. Can you write range comparisons (e.g. WHEN > 100) inside an ABAP CASE statement?
No. WHEN clauses only support discrete value matching or OR groupings of constants. For relational range comparisons (>, <, BETWEEN), use an IF-ELSEIF statement or COND #( ... ) expression.
2. What is the modern ABAP 7.4+ inline expression equivalent of a CASE statement?
The SWITCH #( ... WHEN ... THEN ... ELSE ... ) operator expression.
3. What happens if a CASE statement has no WHEN OTHERS block and none of the WHEN clauses match the control variable?
No code block inside the CASE executes. Control jumps immediately to ENDCASE without raising any runtime exception.
Best Practices for Clean Code
- Always Include
WHEN OTHERS: Legacy database records or newly added SAP status codes can introduce unexpected values that will bypass unhandledCASEstatements silently. - Use Global Constants: Avoid hardcoding literal strings like
WHEN 'OR'. Define global constants (e.g.,CONSTANTS co_open TYPE char1 VALUE 'A') to maintain clean, readable code. - Prefer
SWITCHfor Simple Assignments: When assigning a value based on discrete matches, use modernSWITCHinline expressions instead of verbose 15-lineCASEstatements.
Summary
The CASE statement is a foundational multi-branch control structure in SAP ABAP. By mastering value matching, OR groupings, WHEN OTHERS fallbacks, CASE TYPE OF, and modern SWITCH expressions, you can build performant, readable enterprise applications.
Written by Daksh Dedha
SAP Technical ConsultantDaksh is an SAP Technical Consultant specializing in ABAP programming, SAP S/4HANA migrations, Fiori development, and BTP cloud architecture. He authors free, hands-on tutorials to make enterprise SAP education accessible to all developers.
Test Your Knowledge
Loading question...
Quiz Completed
Related Tutorials
SAP ABAP Enhancement Framework — User Exits, BADIs, and Enhancement Points
Master SAP ABAP enhancements. Learn User Exits, Customer Exits, BADIs, Enhancement Points, and Implicit/Explicit Enhancement Spots to modify standard SAP without modifying source code.
ABAP ProgrammingABAP CDS Views — Core Data Services Complete Guide for Beginners
Learn ABAP CDS Views from scratch. Understand how to create CDS views in Eclipse ADT, use annotations, associations, parameters, and build OData services with CDS.
ABAP ProgrammingMessage Handling in SAP ABAP — Complete SE91 Message Classes Guide
Master SAP ABAP message handling. Learn how to create message classes in transaction SE91, use the MESSAGE statement, handle error types A E W I S X, and pass placeholders.
Found this tutorial useful? Share it with your SAP development team.