Oracle PL/SQL - WHILE LOOP Statement


The WHILE LOOP statement runs one or more statements while a condition is true.

It has this structure:

[ label ] WHILE condition LOOP 
END LOOP [ label ]; 

If the condition is true, the statements run and control returns to the top of the loop, where condition is evaluated again.

If the condition is not true, control transfers to the statement after the WHILE LOOP statement.

To prevent an infinite loop, a statement inside the loop must make the condition false or null.

An EXIT, EXIT WHEN, CONTINUE, or CONTINUE WHEN in the statements can cause the loop or the current iteration of the loop to end early.

In the following code, the statements in the first WHILE LOOP statement never run, and the statements in the second WHILE LOOP statement run once.


SQL>--   w w  w.j a v  a 2  s  . co  m
  2    done  BOOLEAN := FALSE;
  3  BEGIN
  4    WHILE done LOOP
  5      DBMS_OUTPUT.PUT_LINE ('This line does not print.');
  6      done := TRUE;  -- This assignment is not made.
  7    END LOOP;
  9    WHILE NOT done LOOP
 10      DBMS_OUTPUT.PUT_LINE ('Hello, world!');
 11      done := TRUE;
 12    END LOOP;
 13  END;
 14  /
Hello, world!

PL/SQL procedure successfully completed.


LOOP UNTIL or do while loop

To simulate do...while loop to do Loop Until or Repeat Until structure, use a basic LOOP statement with an EXIT WHEN statement:

  EXIT WHEN condition; 

Related Topics