Oracle PL/SQL/PL SQL/When
Exit when loop
<source lang="sql">
SQL> declare
2 l_loops number := 0; 3 begin 4 dbms_output.put_line("Before my loop"); 5 6 loop 7 exit when l_loops > 4; 8 dbms_output.put_line("Looped " || l_loops || " times"); 9 l_loops := l_loops + 1; 10 end loop; 11 12 dbms_output.put_line("After my loop"); 13 end; 14 /
Before my loop Looped 0 times Looped 1 times Looped 2 times Looped 3 times Looped 4 times After my loop PL/SQL procedure successfully completed. SQL>
</source>
Use when inside case
<source lang="sql">
SQL> SQL> -- switch case SQL> SQL> SQL> declare
2 l_num number := 7; 3 begin 4 case l_num 5 when 1 then dbms_output.put_line("You selected one"); 6 when 2 then dbms_output.put_line("You selected two"); 7 when 3 then dbms_output.put_line("You selected three"); 8 when 4 then dbms_output.put_line("You selected four"); 9 when 5 then dbms_output.put_line("You selected five"); 10 when 6 then dbms_output.put_line("You selected six"); 11 when 7 then dbms_output.put_line("You selected seven"); 12 when 8 then dbms_output.put_line("You selected eight"); 13 when 9 then dbms_output.put_line("You selected nine"); 14 when 0 then dbms_output.put_line("You selected zero"); 15 --else dbms_output.put_line("You selected more than one digit..."); 16 end case; 17 end; 18 /
You selected seven PL/SQL procedure successfully completed. SQL>
</source>
Use when to catch exceptions
<source lang="sql">
SQL> SQL> -- catch Exception SQL> SQL> declare
2 l_number number; 3 begin 4 l_number := "MY NUMBER"; 5 exception 6 when OTHERS then 7 dbms_output.put_line("Exception caught"); 8 raise; 9 end; 10 /
Exception caught
declare
ERROR at line 1: ORA-06502: PL/SQL: numeric or value error: character to number conversion error ORA-06512: at line 8
SQL>
</source>