FOR Loops

A FOR loop runs a predetermined number of times. The syntax for a FOR loop is as follows:


FOR loop_variable IN [REVERSE] lower_bound..upper_bound LOOP
    statements
END LOOP;

It says:

ItemDescription
loop_variablethe loop variable. The loop variable value is increased or decreased by 1 each time through the loop.
REVERSEthat the loop variable value is to be decremented each time through the loop.
lower_boundthe loop's lower boundary.
upper_boundthe loop's upper boundary.

SQL> DECLARE
  2      v_counter INTEGER;
  3  BEGIN
  4      v_counter := 0 ;
  5      FOR v_counter IN 1..5 LOOP
  6          DBMS_OUTPUT.PUT_LINE(v_counter);
  7      END LOOP;
  8  END;
  9  /
1
2
3
4
5

PL/SQL procedure successfully completed.

SQL>

The following example uses REVERSE:
SQL> DECLARE
  2      v_counter INTEGER;
  3  BEGIN
  4      v_counter := 0 ;
  5      FOR v_counter IN REVERSE 1..5 LOOP
  6       DBMS_OUTPUT.PUT_LINE(v_counter);
  7      END LOOP;
  8  END;
  9  /
5
4
3
2
1

PL/SQL procedure successfully completed.

SQL>
Home »
Oracle »
PL/SQL » 

Related: