Pages

WHILE loop

If we don't actually want to loop indefinitely, the PL/SQL simple LOOP statement risks to be unclear to the code reader.

If we know which codition rules the execution of the loop, we'd better use a WHILE loop instead:

WHILE (...)
LOOP
(...)
END LOOP;

The condition should evaluate to a boolean value. Only if such value is true the loop is carried on. In case of false (or NULL) the point of execution jumps to the next instruction after the end of the loop.

Here is the same loop showed in the previous post rewritten as a WHILE loop:

while l_value != 0
loop
dbms_output.put_line(l_value);
l_value := l_value - 1;
end loop;

There is no automatic conversion from integer to boolean here, so we have to write explicitly the check against zero.

More on loops in chapter 5 of Oracle PL/SQL Programming, fifth edition, by Steven Feuerstein.

No comments:

Post a Comment