PLSQL - Nested Blocks & Scope of variables


 Nested Blocks

declare

v_outer number;

begin

v_outer := 80;

dbms_output.put_line('Outer Block');

declare

v_inner number;

begin

v_inner := 90;

dbms_output.put_line('Inner Block');

dbms_output.put_line('Inner Block variable value ' || v_inner);

end;

dbms_output.put_line('Outer Block variable value ' || v_outer);

end;


Scope of variables

The variable declared in the outer block can be accessed by inner block but inner block variable can not be accessed by outer block.

declare

v_outer number;

begin

v_outer := 100;

declare

v_inner number;

begin

v_inner := 110;

dbms_output.put_line('Inner Block variable value ' || v_inner);

dbms_output.put_line('Outer block variable is accessible in the inner block');

dbms_output.put_line('Outer block variable value ' || v_outer);  

end;

dbms_output.put_line('Outer Block variable value ' || v_outer);

dbms_output.put_line('Inner Block variable value ' || v_inner);

end;


Labels

If the variables names of the outer and inner blocks are same then labels have to be used within the inner block to avoid confusion.

<<outer_block>>

declare

v_salary number;

begin

<<inner_block>> 

declare

v_salary  number := 100;

begin

dbms_output.put_line('Value of the inner block is ' || v_salary);

-- Giving value of v_salary of the inner block to the outer block v_salary

outer_block.v_salary :=inner_block. v_salary;

end;

v_salary := v_salary + 500;

dbms_output.put_line('Value of the outer block is ' || v_salary);

end;

Complete Tutorial

*/

No comments:

Post a Comment