WHILE statement (PL/SQL)

The WHILE statement repeats a set of SQL statements as long as a specified expression is true. The condition is evaluated immediately before each entry into the loop body.

Invocation

This statement can be embedded within a PL/SQL procedure, function, or anonymous block statement.

Authorization

No privileges are required to invoke the WHILE statement; however, the authorization ID of the statement must hold the necessary privileges to invoke the SQL statements that are embedded in the WHILE statement.

Syntax

Read syntax diagramSkip visual syntax diagramWHILE expressionLOOPstatementsEND LOOP

Description

expression
Specifies an expression that is evaluated immediately before each entry into the loop body to determine whether or not the loop is to be executed. If the expression is logically true, the loop is executed. If the expression is logically false, loop processing ends. An EXIT statement can be used to terminate the loop while the expression is true.
statements
Specifies the PL/SQL and SQL statements that are executed each time that the loop is processed.

Example

The following example shows a basic WHILE statement within an anonymous block:
DECLARE
  sum INTEGER := 0;
BEGIN
  WHILE sum < 11 LOOP
    sum := sum + 1;
  END LOOP;
END
The WHILE statement within this anonymous block executes until sum is equal to 11; loop processing then ends, and processing of the anonymous block proceeds to completion.