Oracle PL/SQL - FOR LOOP Statement References Variable with Same Name as Index

Introduction

The following code shows how to allow the statement inside the loop to reference the variable declared in the enclosing block.

Demo

SQL>
SQL> <<main>>  -- Label block.
  2  DECLARE
  3    i NUMBER := 5;
  4  BEGIN--  w ww .j  a v  a 2 s .  co  m
  5    FOR i IN 1..3 LOOP
  6      DBMS_OUTPUT.PUT_LINE('local: ' || TO_CHAR(i) || ', global: ' ||TO_CHAR(main.i)  -- Qualify reference with block label.
  7      );
  8    END LOOP;
  9  END main;
 10  /
local: 1, global: 5
local: 2, global: 5
local: 3, global: 5

PL/SQL procedure successfully completed.

SQL>

Here, the indexes of the nested FOR LOOP statements have the same name.

The inner loop references the index of the outer loop by qualifying the reference with

Related Topic