Sub topic 14
CASE in PL/SQL: statement versus expression
This chapter assumes you know basic SELECT statements, Oracle data types, NULL, variables, and simple PL/SQL blocks. PL/SQL supports two related forms:
- A CASE expression calculates and returns one value.
- A CASE statement chooses which PL/SQL statements to run.
The syntax and behavior are similar, but they are used for different jobs.
CASE expressions return values
Use a CASE expression when you need a value for an assignment, output column, function argument, or another expression. The expression can be simple or searched.
DECLARE
v_salary NUMBER := 8500;
v_band VARCHAR2(10);
BEGIN
v_band := CASE
WHEN v_salary < 5000 THEN 'Low'
WHEN v_salary < 10000 THEN 'Medium'
ELSE 'High'
END;
DBMS_OUTPUT.PUT_LINE('Salary band: ' || v_band);
END;
/The CASE expression returns a VARCHAR2 value. PL/SQL assigns that value to v_band. The expression ends with END, without the word CASE.
You can also use a CASE expression directly in a SQL statement:
SELECT employee_id,
salary,
CASE
WHEN salary < 5000 THEN 'Low'
WHEN salary < 10000 THEN 'Medium'
ELSE 'High'
END AS salary_band
FROM employees;CASE statements run PL/SQL statements
Use a CASE statement when each branch must perform an action, such as assigning several variables, calling a procedure, or inserting a row.
This is a simple CASE statement. It compares one expression with several values.
DECLARE
v_grade VARCHAR2(1) := 'B';
v_text VARCHAR2(20);
BEGIN
CASE v_grade
WHEN 'A' THEN
v_text := 'Excellent';
DBMS_OUTPUT.PUT_LINE('Top grade');
WHEN 'B' THEN
v_text := 'Good';
DBMS_OUTPUT.PUT_LINE('Passing grade');
ELSE
v_text := 'Review';
DBMS_OUTPUT.PUT_LINE('Needs review');
END CASE;
DBMS_OUTPUT.PUT_LINE(v_text);
END;
/A CASE statement ends with END CASE;. Each THEN branch contains one or more PL/SQL statements, and each statement ends with a semicolon.
A searched CASE statement tests conditions directly:
DECLARE
v_salary NUMBER := 12000;
BEGIN
CASE
WHEN v_salary >= 10000 THEN
DBMS_OUTPUT.PUT_LINE('Approve standard benefits');
WHEN v_salary >= 5000 THEN
DBMS_OUTPUT.PUT_LINE('Approve basic benefits');
ELSE
DBMS_OUTPUT.PUT_LINE('Review eligibility');
END CASE;
END;
/Oracle checks the WHEN clauses from top to bottom and runs the first matching branch.
The important difference when nothing matches
A CASE expression with no matching WHEN and no ELSE returns NULL.
A CASE statement with no matching WHEN and no ELSE raises the predefined CASE_NOT_FOUND exception. Add an ELSE branch when an unmatched value is possible.
| Form | Purpose | Ending | No match without ELSE |
|---|---|---|---|
| CASE expression | Returns one value | `END` | Returns `NULL` |
| CASE statement | Runs PL/SQL statements | `END CASE;` | Raises `CASE_NOT_FOUND` |
Exercise
What happens when a PL/SQL CASE statement has no matching WHEN branch and no ELSE branch?
Show answer
It raises the CASENOTFOUND exception. Add an ELSE branch to handle unmatched values.