Pages

Simple LOOP

The simplest way of iterating the execution of a statement in PL/SQL is achieved through the LOOP statement. And the simplest form of LOOP is this:

loop
(...)
end loop;

We normally want to stop a loop execution, and there are two polite ways of terminating a simple loop: through the EXIT and the EXIT WHEN statements.

Here is an example of a LOOP in an anonymous block terminated by EXIT:

declare
l_value integer := 3;
begin
loop
dbms_output.put_line(l_value);
if l_value = 0 then
exit;
else
l_value := l_value - 1;
end if;
end loop;
end;

We could easily rewrite the loop using EXIT WHEN, making it more readable:

loop
dbms_output.put_line(l_value);
exit when l_value = 0;

l_value := l_value - 1;
end loop;

As you can see, EXIT WHEN is merely a rewriting of an IF (condition) THEN EXIT statement.

Chapter 5 of Oracle PL/SQL Programming, fifth edition, by Steven Feuerstein is about loops.

No comments:

Post a Comment