Nested Block in PLSQL
Nested Block in PLSQL
Nested Blocks:
SQL> DECLARE x NUMBER; BEGIN x := 80; DBMS_OUTPUT.PUT_LINE('abc'); DECLARE y NUMBER; BEGIN y := 90; DBMS_OUTPUT.PUT_LINE ('Inner Block variable value '|| y); END; DBMS_OUTPUT.PUT_LINE ('Outer Block variable value '|| x); END;
Output:
abc Inner Block variable value 90 Outer Block variable value 80
Scope of variables:
A variable declared in the outer block is accessible in the inner block. But a variable declared in the inner block is accessible only in the inner block.
SQL> DECLARE outer NUMBER; BEGIN outer := 80; DECLARE inner NUMBER; BEGIN inner := 90; DBMS_OUTPUT.PUT_LINE('Inner Block variable value ' || inner); DBMS_OUTPUT.PUT_LINE ('Outer block variable is accessible in the inner block'); DBMS_OUTPUT.PUT_LINE ('Outer block variable value ' || outer); END; DBMS_OUTPUT.PUT_LINE ('Outer Block variable value ' || outer); DBMS_OUTPUT.PUT_LINE ('Inner Block variable value ' || inner); END; /
Output:
DBMS_OUTPUT.PUT_LINE ('Inner Block variable value: ' || inner); * ERROR at line 14: ORA-06550: line 14, column 57: PLS-00201: identifier 'INNER' must be declared ORA-06550: line 14, column 1: PL/SQL: Statement ignored
Note: The above problem occurs, because Parent/Outer block can not access the
variable declared in the Child/Inner block. So can be avoided as follows. SQL> DECLARE outer NUMBER; BEGIN outer := 80; DECLARE inner NUMBER; BEGIN inner := 90; DBMS_OUTPUT.PUT_LINE('Inner Block variable value: ' || inner); DBMS_OUTPUT.PUT_LINE('Outer block variable is accessible in the inner block'); DBMS_OUTPUT.PUT_LINE('Outer block variable value: ' ||
outer); END; DBMS_OUTPUT.PUT_LINE ('Outer Block variable value: ' || outer); --DBMS_OUTPUT.PUT_LINE ('Inner Block variable value: ' || inner); END; /
Output:
Inner Block variable value: 90 Outer block variable is accessible in the inner block Outer block variable value: 80 Outer Block variable value: 80