HomeOracle Page 5 - Database Interaction with PL/SQL: User defined Exceptions, Nested Blocks
Nested blocks with local variable declarations - Oracle
This is part 7 of a series of articles focusing on database interactions with Oracle PL/SQL. In my previous article, I gave an introduction to exception handling and went through some predefined exceptions. In this article, we will focus on user defined exceptions in PL/SQL and some tips for working with exceptions efficiently.
This is just an extension to the previous section. I will show you the sample example in the previous section, with a few variations in nested blocks. The only issue I wanted to address here is that the nested blocks can have their own local declarations without having any relation to their parent or other friendly (parallel) blocks.
Declare v_empno1 emp.empno%Type := &empno1; v_empno2 emp.empno%Type := &empno2; Begin
Declare v_ename1 emp.ename%Type; Begin Select ename into v_ename1 From emp Where empno=v_empno1; dbms_output.put_line('Name: '||v_ename1); Exception When no_data_found then dbms_output.put_line('Employee not found with '||v_empno1); End;
Declare v_ename2 emp.ename%Type; Begin Select ename into v_ename2 From emp Where empno=v_empno2; dbms_output.put_line('Name:'||v_ename2); Exception When no_data_found then dbms_output.put_line('Employee not found with '||v_empno2); End;
End;
From the above program, you can clearly observe that every nested block has its own DECLARE section. The variable 'v_ename1' in the first nested block cannot be accessed beyond the first block (in this case, cannot be accessed by the parent block or even the second block) and the case of 'v_ename2' is similar. You can also localize all variables (based on the situation) and remove the declarations section from the parent block, as shown in the following example:
Begin
Declare v_ename1 emp.ename%Type; v_empno1 emp.empno%Type := &empno1; Begin Select ename into v_ename1 From emp Where empno=v_empno1; dbms_output.put_line('Name: '||v_ename1); Exception When no_data_found then dbms_output.put_line('Employee not found with '||v_empno1); End;
Declare v_ename2 emp.ename%Type; v_empno2 emp.empno%Type := &empno2; Begin Select ename into v_ename2 From emp Where empno=v_empno2; dbms_output.put_line('Name:'||v_ename2); Exception When no_data_found then dbms_output.put_line('Employee not found with '||v_empno2); End;
End;
That is how we can separate every aspect of the program within a PL/SQL block into several blocks. And each of these blocks can be further separated or nested any number of times.