WHILE-LOOP
The WHILE-LOOP statement relates a condition with the series of statements enclosed by the keywords LOOP and END LOOP, as shown:
WHILE condition LOOP
sequence_of_statements
END LOOP;
Before each of the iteration of the loop, the condition is computed. If the condition is true, then the series of statements is executed, then the control resumes at the top of the loop. When the condition is false or null, the loop is then bypassed and control passes to the next statement. An illustration is shown below:
WHILE total <= 25000 LOOP
...
SELECT sal INTO salary FROM emp WHERE...
total := total + salary;
END LOOP;
The number of iterations depends on the condition and is not known until the loop done. The condition is tested at the top of the loop, so the series might execute zero times. In the last illustration, if the initial value of total is bigger than 25000, the condition is false and the loop is bypassed.
A few languages have a LOOP UNTIL or REPEAT UNTIL structure, that tests the condition at the bottom of the loop rather than at the top. So, the sequence of the statements is executed at least once. The PL/SQL has no such structure, but you can easily build one, as shown:
LOOP
sequence_of_statements
EXIT WHEN boolean_expression;
END LOOP;
To make sure that a WHILE loop executes at least once, then use an initialized Boolean variable in the condition which is as shown below:
done := FALSE;
WHILE NOT done LOOP
sequence_of_statements
done := boolean_expression;
END LOOP;
The statement inside the loop should assign a new value to the Boolean variable. Or else, you have an infinite loop. For illustration, the following LOOP statements are logically equal:
WHILE TRUE LOOP | LOOP
... | ...
END LOOP; | END LOOP;