Introduction

The EXIT WHEN statement exits the current iteration of a loop when the condition in its WHEN clause is true.

It transfers control to the end of either the current loop or an enclosing labeled loop.

Each time control reaches the EXIT WHEN statement, the condition in its WHEN clause is evaluated.

If the condition is not true, the EXIT WHEN statement does nothing.

To prevent an infinite loop, a statement inside the loop must make the condition true.

In the following code, the EXIT WHEN statement inside the basic LOOP statement transfers control to the end of the current loop when x is greater than 3.

Demo

SQL>
SQL> --Basic LOOP Statement with EXIT WHEN Statement
SQL> DECLARE
  2    x NUMBER := 0;
  3  BEGIN-- from   w ww .java  2  s .c o m
  4      LOOP
  5          DBMS_OUTPUT.PUT_LINE('Inside loop:  x = ' || TO_CHAR(x));
  6          x := x + 1;  -- prevents infinite loop
  7          EXIT WHEN x > 3;
  8  END LOOP;
  9    -- After EXIT statement, control resumes here
 10    DBMS_OUTPUT.PUT_LINE('After loop:  x = ' || TO_CHAR(x));
 11  END;
 12  /
Inside loop:  x = 0
Inside loop:  x = 1
Inside loop:  x = 2
Inside loop:  x = 3
After loop:  x = 4

PL/SQL procedure successfully completed.

SQL>

Related Topic