我有一个带OUT
参数的 PL/SQL 过程。OUT
即使引发错误,如何强制写入参数值?引发错误时是否有另一种返回值的机制?
问问题
7605 次
2 回答
6
为了扩展@APC的答案,文档说:
如果您成功退出子程序,PL/SQL 将值分配给 OUT 参数。但是,如果您以未处理的异常退出,PL/SQL 不会将值分配给 OUT 参数(除非它们是 NOCOPY 参数)。
以下是一些可能有助于说明的示例:
SQL> set serveroutput on
SQL> REM Example 1 -- OUT parameter value is unchanged if an exception was raised after value was assigned
SQL> declare
2 x number := 1;
3 procedure p(x out number)
4 as
5 begin
6 x := 2;
7 raise program_error;
8 end p;
9 begin
10 p(x);
11 exception
12 when program_error then
13 dbms_output.put_line
14 (
15 case
16 when x is null then 'null'
17 else to_char(x)
18 end
19 );
20 end;
21 /
1
PL/SQL procedure successfully completed.
SQL> REM Example 2 -- OUT parameter value is unchanged if value was set in exception handler and exception was then re-raised
SQL> declare
2 x number := 1;
3 procedure p(x out number)
4 as
5 begin
6 x := 2;
7 raise program_error;
8 exception
9 when program_error then
10 x := 3;
11 raise;
12 end p;
13 begin
14 p(x);
15 exception
16 when program_error then
17 dbms_output.put_line
18 (
19 case
20 when x is null then 'null'
21 else to_char(x)
22 end
23 );
24 end;
25 /
1
PL/SQL procedure successfully completed.
SQL> REM Example 3 -- OUT parameter value is changed if value was set in exception handler and exception was not re-raised
SQL> declare
2 x number := 1;
3 procedure p(x out number)
4 as
5 begin
6 x := 2;
7 raise program_error;
8 exception
9 when program_error then
10 x := 3;
11 end p;
12 begin
13 p(x);
14 dbms_output.put_line
15 (
16 case
17 when x is null then 'null'
18 else to_char(x)
19 end
20 );
21 end;
22 /
3
PL/SQL procedure successfully completed.
SQL> REM Example 4 -- OUT NOCOPY parameter value is changed if an exception was raised
SQL> declare
2 x number := 1;
3 procedure p(x out nocopy number)
4 as
5 begin
6 x := 2;
7 raise program_error;
8 end p;
9 begin
10 p(x);
11 exception
12 when program_error then
13 dbms_output.put_line
14 (
15 case
16 when x is null then 'null'
17 else to_char(x)
18 end
19 );
20 end;
21 /
2
PL/SQL procedure successfully completed.
于 2012-11-02T13:46:26.423 回答
4
当 PL/SQL 程序引发异常时,Oracle 不会为 OUT 参数赋值。如果这是一个安全功能,因为它为我们提供了已知且一致状态的所有参数
然而,有时这不是我们想要的。例如,我们可能希望使用 OUT 参数将错误消息或其他有用信息传递给调用程序。我们可以在程序的EXCEPTIONS部分设置OUT参数。这些值被传递出去(除非处理程序本身引发异常)。
于 2012-11-02T12:23:16.277 回答