Scope of Variables

Contact Us or call 1-877-932-8228
Scope of Variables

Scope of Variables

The scope of an identifier is the area within a program unit where it can be referenced.

Code Sample:

Nested-Blocks/Demos/nested_block_variable_scope.sql
declare
  x NUMBER := 1;
begin

   dbms_output.put_line('In the main block.  x = '
                        || x);

   declare 
     x NUMBER := 2;
   begin
   
    dbms_output.put_line('In a nested block. x = '
                         || x);
   end;
   
   dbms_output.put_line('In the main block.  x = '
                        || x);
   
end;

Code Explanation

This example shows how a variable with the same name as a variable in an enclosing block effectively masks the outer variable. When the example is run, the value of x varies based upon the context of the DBMS_OUTPUT.PUT_LINE call.

Code Sample:

Nested-Blocks/Demos/nested_block_variable_scope2.sql
declare
  x NUMBER := 1;
begin

   dbms_output.put_line('In the main block.  x = '
                        || x);

   declare 
     --Removed the local variable x 
   begin
    dbms_output.put_line('In a nested block. x = '
                         || x);
   end;
   
   dbms_output.put_line('In the main block.  x = '
                        || x);
   
end;

Code Explanation

In this example, the local variable x from the inner block is removed. As a result the variable from the outer block is visible.

Code Sample:

Nested-Blocks/Demos/nested_block_variable_scope_qualifier.sql
<<outer_block>>
declare
  x NUMBER := 1;
begin

   dbms_output.put_line('In the main block.  x = '
                        || x);

   declare 
     x varchar(1) := 'a';
   begin
    dbms_output.put_line('In nested block. outer x = '
                         || outer_block.x);
                         
    dbms_output.put_line('In nested block. inner x = '
                         || x); 
   end;
   
   dbms_output.put_line('In the main block.  x = '
                        || x);
   
end;

Code Explanation

This example demonstrates the use of a labeled block which is used to identify a variable that is named in two different scopes within the script. NOTE: There is a bug in some versions of Oracle software that causes an error (ORA-600) network disconnect when outer labeled blocks are used. This was left in the lesson to emphasize the point that the Oracle database can have bugs that need to be repaired through patches applied by a DBA.

Next