Oracle PL/SQL - Nested, Labeled Basic LOOP Statements with EXIT WHEN Statements

Introduction

In the following code, one basic LOOP statement is nested inside the other, and both have labels.

The inner loop has two EXIT WHEN statements; one that exits the inner loop and one that exits the outer loop.

Demo

SQL>
SQL> DECLARE--   w ww .j av a2 s.  co  m
  2    s  PLS_INTEGER := 0;
  3    i  PLS_INTEGER := 0;
  4    j  PLS_INTEGER;
  5  BEGIN
  6    <<outer_loop>>
  7    LOOP
  8      i := i + 1;
  9      j := 0;
 10      <<inner_loop>>
 11      LOOP
 12        j := j + 1;
 13        s := s + i * j; -- Sum several products
 14        EXIT inner_loop WHEN (j > 6);
 15        EXIT outer_loop WHEN ((i * j) > 20);
 16      END LOOP inner_loop;
 17    END LOOP outer_loop;
 18    DBMS_OUTPUT.PUT_LINE ('The sum of products equals: ' || TO_CHAR(s));
 19  END;
 20  /
The sum of products equals: 252

PL/SQL procedure successfully completed.

SQL>

Related Topic