PL/SQL Control Structures
if-then-else
if boolean_expression then
sequence of statements;
[elsif boolean_expression then
sequence of statements;]
[else
sequence of statements;]
end if;
case
Ordinary case statement
casetest_variable
when value_1 then sequence_of_statements_1;
when value_2 then sequence_of_statements_2;
...
when value_N then sequence_of_statements_N;
[else else_sequence;]
end case;
Labeled case statement
<<case_label>>
casetest_variable
when value_1 then sequence_of_statements_1;
when value_2 then sequence_of_statements_2;
...
when value_N then sequence_of_statements_N;
[else else_sequence;]
end case case_label ;
Searched case statement
case
when boolean_expression_1 then sequence_of_statements_1;
when boolean_expression_1 then sequence_of_statements_2;
...
when boolean_expression_1 then sequence_of_statements_N;
[else else_sequence;]
end case;
Simple loop
loop
sequence_of_statements;
end loop;
This statements will loop forever. To exit of the loop we can use either the exit
command:
loop
if i < 10 then
dbms_output.put_line('line number' || to_char(i));
else
exit;
end if;
end loop;
or a conditional exit command
exit when boolean_condition;
while loop
while boolean_condition loop
sequence_of_statements;
end loop;
for loop
for loop_counter in [reverse] low_bound..high_bound loop
sequence_of_statements;
end loop;
where loop_counter is an implicitly declared index variable (you do not need to declare it, Oracle does it for you)
and low_bound and high_bound specify the number of iterations. If the reverse keyword is present
in the for loop, the loop index will iterates from the high value to the low value.
Labeling loops
Loops themselves can be labeled. If so, the labels can be used on the exit statement to indicate which loop
to be exited:
<<outer_loop>>
for i in 1..10 loop
dbms_output.put_line('Outer loop. Iteration #' || i);
j := 0;
<<inner_loop>>
while j < i**2 loop
dbms_output.put_line('Inner loop. Iteration #' || j);
j := j + 1;
exit outer_loop when j > 12;
end loop inner_loop;
end loop outer_loop;
null as a statement