开发写了个存储过程需要我们审批,发现子程序中使用了异常处理语句,
通过以下实验说明这种写法的问题:
SQL> create table test_number(test_id number);
Table created
Executed in 0.031 seconds
不使用子程序,正常执行:
SQL> declare
2 v_err_mess varchar2(200);
3 n_count number;
4 begin
5 select count(1) into n_count from test_number;
6 dbms_output.put_line(n_count);
7 exception
8 when others then
9 v_err_mess:=sqlcode||' '||sqlerrm;
10 dbms_output.put_line(v_err_mess);
11 end;
12 /
0
PL/SQL procedure successfully completed
不使用子程序,异常执行:
SQL> declare
2 v_err_mess varchar2(200);
3 n_count number;
4 begin
5 select test_id into n_count from test_number;
6 dbms_output.put_line(n_count);
7 exception
8 when others then
9 v_err_mess:=sqlcode||' '||sqlerrm;
10 dbms_output.put_line(v_err_mess);
11 end;
12 /
100 ORA-01403: 未找到任何数据
PL/SQL procedure successfully completed
使用子程序,在子程序中进行异常处理:
可以看到,在外层调用中无法获取子程序异常处理中的赋值
SQL>
SQL> declare
2 v_err_mess varchar2(200);
3 n_count number;
4 begin
5 begin
6 select test_id into n_count from test_number;
7 dbms_output.put_line(n_count);
8 exception
9 when others then
10 v_err_mess:=sqlcode||' '||sqlerrm;
11 dbms_output.put_line(v_err_mess);
12 end;
13
14 dbms_output.put_line('inner layer values:'||n_count);
15 exception
16 when others then
17 v_err_mess:='out_layer:'||sqlerrm;
18 dbms_output.put_line(v_err_mess);
19 end;
20 /
100 ORA-01403: 未找到任何数据
inner layer values:
PL/SQL procedure successfully completed
使用子程序,在子程序中进行正常处理:
可以看到,在外层调用中可以获取子程序中的赋值
SQL> declare
2 v_err_mess varchar2(200);
3 n_count number;
4 begin
5 begin
6 select count(1) into n_count from test_number;
7 dbms_output.put_line(n_count);
8 exception
9 when others then
10 v_err_mess:=sqlcode||' '||sqlerrm;
11 dbms_output.put_line(v_err_mess);
12 end;
13
14 dbms_output.put_line('inner layer values:'||n_count);
15 exception
16 when others then
17 v_err_mess:='out_layer:'||sqlerrm;
18 dbms_output.put_line(v_err_mess);
19 end;
20 /
0
inner layer values:0
PL/SQL procedure successfully completed
以上实验
内层程序中发生异常后,不会继续执行外层程序的语句。
可以在最外层进行异常处理。
来自 “ ITPUB博客 ” ,链接:/26451536/viewspace-1815947/,如需转载,请注明出处,否则将追究法律责任。