Like real life in programming sometimes we need to execute some code on a specific condition, PL/SQL CASE statement allows us to execute a sequence of instructions based on a selector (A variable, function, expression, etc)
and if the selector value is equal to value or expression in WHEN clause then corresponding THEN clause will execute and process the statements only if the condition is true
The basic syntax for the CASE statement is as follows
CASE (Selector)
WHEN condition 1 THEN
statements to execute…
WHEN condition 2 THEN
statements to execute…
…
WHEN condition N THEN
statements to execute…
ELSE
statements to execute…
END;
See this example of using a CASE statement in PL/SQL, Here I am defining 3 cases for High, Medium, Normal priority, and passing ‘M’ as value to check the CASE statement output. This is a basic example of using the CASE statement and in the same way, you can write complex and nested CASE statements in PL/SQL
DECLARE --Variable declared as selector priority char(1):='M'; BEGIN -- selector passed in CASE CASE priority -- Checking conditions for the value of selector WHEN 'H' THEN dbms_output.put_line('High Priority'); WHEN 'M' THEN dbms_output.put_line('Medium Priority'); WHEN 'N' THEN dbms_output.put_line('Normal Priority'); END CASE; END;
The Output in SQL developer is Medium Priority because of the passed value in character was ‘M’
This is how we use conditions and CASE statement in PL/SQL. Also, read previous articles for a better understanding
Cheers 🙂 Happy Learning