PL/SQL User's Guide and Reference

Contents Index Home Previous Next

Sample 1. FOR Loop

The following example uses a simple FOR loop to insert ten rows into a database table. The values of a loop index, counter variable, and either of two character strings are inserted. Which string is inserted depends on the value of the loop index.

Input Table

Not applicable.

PL/SQL Block

-- available online in file SAMPLE1

DECLARE
   x NUMBER := 100;
BEGIN
   FOR i IN 1..10 LOOP
      IF MOD(i,2) = 0 THEN     -- i is even
         INSERT INTO temp VALUES (i, x, 'i is even');
      ELSE
         INSERT INTO temp VALUES (i, x, 'i is odd');
      END IF;
      x := x + 100;
   END LOOP;
   COMMIT;
END;

Output Table

SQL> SELECT * FROM temp ORDER BY col1;

 
 COL1    COL2    MESSAGE
 ----- -------    ---------
     1     100    i is odd
     2     200    i is even
     3     300    i is odd
     4     400    i is even
     5     500    i is odd
     6     600    i is even
     7     700    i is odd
     8     800    i is even
     9     900    i is odd
    10    1000    i is even

 10 records selected.


Contents Index Home Previous Next