PL/SQL Looping Statements

LOOP, WHILE Loop, FOR Loop

A basic LOOP command will continue until 'condition' evaluates to true
(condition is a boolean var)

LOOP
   STATEMENT1;
   ...
   EXIT [WHEN condition];
END LOOP;

The only difference between LOOP and WHILE is that the
condition is evaluated at the start of each iteration.

WHILE condition LOOP
   statement1;
   statement2;
...
END LOOP;

A PL/SQL FOR Loop will implicitly declare a counter,
the counter can only be referenced within the loop. 
Don't try to change the counter's value using code.

FOR loop

FOR counter in [REVERSE]
   lower_bound..upper_bound LOOP
   statement1;
   statement2;
...
END LOOP;


The 3 loop commands above (LOOP, WHILE, FOR) can be Nested...

To give each loop a specific name - put the name in double
angle brackets << >>
Put this name definition on the line immediately before each LOOP 

<<Main_loop>>
LOOP
...
   <<sub_loop>>
   LOOP
   ...
   END LOOP sub_loop;

END LOOP Main_loop;


When PL/SQL code contains labels like the above it is also possible to GOTO a given label:

e.g.
GOTO Main_loop

This is generally poor programming practice - and some destinations, such as the middle of a loop, won't work.

Related Commands:

Cursor FOR loop - EXIT -

 
Copyright © 1999-2024 SS64.com
Some rights reserved