Oracle PL/SQL Tutorial/PL SQL Programming/Variable Scope

Материал из SQL эксперт
Версия от 10:08, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Controlling scope with a variable declaration

By definition, the scope of a variable is a region of a program unit from which you can reference the variable.

A variable is local to the block where it is declared.

A variable is global to all sub-blocks of the block where it is declared.

In the following code, variable V_STR1_main is local for the block labeled <<MAIN>> and global for the

block labeled <>. Variable V_STR1_sub is visible only in the block <>.</p>

SQL> <<MAIN>>
  2  declare
  3      v_str1_main VARCHAR2(10);
  4  begin
  5      v_str1_main :="ABC";              -- local
  6      <<SUB>>
  7      declare
  8          v_str1_sub VARCHAR2(1);
  9      begin
 10          v_str1_main:="ABC";           -- local
 11          v_str1_sub:="A";             -- global and visible
 12      end;
 13      v_str1_main :="ABC";              -- local
 14  end;
 15  /
PL/SQL procedure successfully completed.
SQL>


Scope Rules

  1. Scope means the range of code within which a given identifier can be referenced.
  2. An identifier can be referenced only by code executing inside the block in which the identifier was declared.
  3. An identifier could be a variable name, or a procedure name, function name.

<p>The following example illustrates the scope of various identifiers.</p>



SQL> SET SERVEROUTPUT ON
SQL> DECLARE
  2    a_name  VARCHAR2(30) := "James";
  3  PROCEDURE name_print IS
  4  BEGIN
  5    DBMS_OUTPUT.PUT_LINE(a_name);
  6  END;
  7
  8    BEGIN
  9       DBMS_OUTPUT.PUT_LINE(a_name);
 10    DECLARE
 11       b_name  VARCHAR2(30) := "Jenny";
 12
 13     BEGIN
 14         DBMS_OUTPUT.PUT_LINE("Inside nested block");
 15         DBMS_OUTPUT.PUT_LINE(a_name);
 16         DBMS_OUTPUT.PUT_LINE(b_name);
 17         name_print;
 18     END;
 19     DBMS_OUTPUT.PUT_LINE("Back in the main block");
 20     --b_name is not defined in this block.
 21     --DBMS_OUTPUT.PUT_LINE(b_name);
 22     name_print;
 23  END;
 24   /
James
Inside nested block
James
Jenny
James
Back in the main block
James
PL/SQL procedure successfully completed.
SQL>