PL/SQL: Missing ELSE in CASE-statement

What happens if we miss out the ELSE in a CASE statement? If your answer is “nothing”, then you might be up for a surprise. If we don´t include an ELSE-statement in a IF-statement, and the boolean expression evolves to false, then you´re completly right – nothing happens! The code will continue running after the IF-statement.
Example:

...
IF (1=2) THEN
   DBMS_OUTPUT.PUT_LINE('This line will never be ran!');
END IF;

DBMS_OUTPUT.PUT_LINE('This line is run!');

...

The code above runs without executing anything in the IF-statement. Then continuing running the statements after the IF-statement.

Ommitting the ELSE in a CASE-statement is another story. Now Oracle will implicit add the following ELSE-statement:

  ELSE
     RAISE CASE_NOT_FOUND;

Knowing this we realize that a missing ELSE in a CASE statement gives a totaly different meaning than a missing ELSE in a IF-statement.

...
CASE WHEN (1=2) THEN
   DBMS_OUTPUT.PUT_LINE('This line will never be executed!');
END;

DBMS_OUTPUT.PUT_LINE('Neighter will this line!');

...

In the example above the statement after the CASE-statement will not be executed, because an exception is raised.

Eksempel:

set serveroutput on
begin
  case when (1=2) then
    dbms_output.put_line('This line is not executed!');
  end case;
  
  dbms_output.put_line('But what about this line?');
  
exception
    when case_not_found then
        dbms_output.put_line('Error: CASE_NOT_FOUND');
end;

Output:
-------------------------------
Error: CASE_NOT_FOUND
PL/SQL procedure successfully completed.

Post a Comment

Your email is never published nor shared. Required fields are marked *