pl/sql: exit an enclosing loop (leaving a labeled loop)


You can leave a loop in pl/sql by specifying a nice litte label to the loop section.
For example: <<firstloop>>

When labeling, you can exit the loop at any time. In following example, lets give the first loop the label <<firstloop>> and so on…
The third loop contains an exit statement when reaching the value of 2. With this exit the control goes back to the end of the first loop!
Usually an exit without labels would only exit the third loop. The first and second loop would run forward.

With this pl/sql label we can skip all of them!

Here’s the sample pl/sql code:

begin
dbms_output.put_line('start first loop');
<<firstloop>>
for a in 1..3
loop
dbms_output.put_line('a=' ||a);
<<secondloop>>
for b in 1..3
loop
dbms_output.put_line(' b=' ||b);
<<thirdloop>>
for c in 1..3
loop
dbms_output.put_line(' c=' ||c);
exit firstloop when c=2;
end loop thirdloop;
end loop secondloop;

end loop firstloop;
end;

Result:

start first loop
a=1
b=1
c=1
c=2

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top