Sub topic 2
The Searched CASE Statement
This chapter assumes you know basic SQL, the DECLARE, BEGIN, EXCEPTION, END structure of an anonymous block, declaring scalar variables, and running a script with DBMS_OUTPUT enabled.
A searched CASE statement tests a list of Boolean conditions in order and runs the first branch whose condition is TRUE. It has no selector expression after the CASE keyword.
DECLARE
l_score NUMBER := 85;
BEGIN
CASE
WHEN l_score >= 90 THEN DBMS_OUTPUT.PUT_LINE('High');
WHEN l_score >= 70 THEN DBMS_OUTPUT.PUT_LINE('Medium');
ELSE DBMS_OUTPUT.PUT_LINE('Low');
END CASE;
END;
/This block prints Medium. A condition that evaluates to NULL is not TRUE, so it is skipped.
CASE Expressions Versus CASE Statements
A CASE statement runs statements and ends with END CASE. A CASE expression returns a value and ends with END, so you can assign it to a variable.
DECLARE
l_score NUMBER := 85;
l_label VARCHAR2(10);
BEGIN
l_label := CASE
WHEN l_score >= 90 THEN 'High'
WHEN l_score >= 70 THEN 'Medium'
ELSE 'Low'
END;
DBMS_OUTPUT.PUT_LINE('Level: ' || l_label);
END;
/Handling CASE_NOT_FOUND
If no WHEN condition is TRUE and the CASE statement has no ELSE, PL/SQL raises CASE_NOT_FOUND. A CASE expression with no match raises the same error.
DECLARE
l_code VARCHAR2(1) := 'X';
BEGIN
CASE l_code
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN DBMS_OUTPUT.PUT_LINE('Inactive');
END CASE;
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No WHEN branch matched and there is no ELSE');
END;
/The Basic LOOP with EXIT and EXIT WHEN
The basic LOOP repeats its body until an EXIT or EXIT WHEN statement leaves it. The EXIT WHEN test runs on each pass.
DECLARE
l_n PLS_INTEGER := 0;
l_total PLS_INTEGER := 0;
BEGIN
LOOP
l_n := l_n + 1;
EXIT WHEN l_n > 3;
l_total := l_total + l_n;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total: ' || l_total);
END;
/This block prints Total: 6.
Repeating While a Condition Holds: WHILE LOOP
A WHILE LOOP tests its condition before each iteration. If the condition is FALSE or NULL at the start, the body never runs.
DECLARE
l_n PLS_INTEGER := 10;
BEGIN
WHILE l_n > 0 LOOP
l_n := l_n - 4;
END LOOP;
DBMS_OUTPUT.PUT_LINE('After WHILE: ' || l_n);
END;
/This block prints After WHILE: -2.
Exercise
Exercise
In the CASENOTFOUND example, what does the block print if l_code is set to 'A'?
Show answer
It prints "Active". The first WHEN branch matches, so the handler never runs.