[英]Identify when a function is executed in a SQL Query or in a PL/SQL procedure
Is there any way to identify when a pl/sql function is executed in SQL Query and when is executed in a procedure or PL/SQL anonymous block?有什么方法可以识别何时在 SQL 查询中执行 pl/sql 函数以及何时在过程或 PL/SQL 匿名块中执行? (I don't want to pass any parameter for manual identification)
(我不想传递任何参数进行手动识别)
The main reason I need that is when a function is executed in a SQL query I wouldn't like to raise an exception in case of failure, I would be satisfied just with a returned value NULL.我需要它的主要原因是当在 SQL 查询中执行函数时,我不想在失败的情况下引发异常,我只会对返回值 NULL 感到满意。 But the same function when is executed in pl/sql script I want to raise exception.
但是在 pl/sql 脚本中执行相同的函数时我想引发异常。
Thank you in advance.先感谢您。
Why don't you add a parameter to the function to indicate whether or not to throw an exception/return null?为什么不给函数添加一个参数来指示是否抛出异常/返回空值? When you call the function you can choose the behaviour you need.
当您调用该函数时,您可以选择所需的行为。
create or replace function do_something(p_parameter1 < some_type >
,p_raise_exception varchar2 default 'Y') return < sometype > is
begin
--.. calculating .. .
return result;
exception
when others then
if p_raise_exception is 'Y'
then
raise;
else
return null;
end if;
end;
Alternatively owa_util seems to provide some functionality you can use.或者 owa_util 似乎提供了一些您可以使用的功能。
create or replace function do_something(p_parameter1 < some_type >) return < sometype > is
l_owner varchar2(100);
l_name varchar2(100);
l_lineno number;
l_caller_t varchar2(100);
begin
--.. calculating .. .
return result;
exception
when others then
owa_util.who_called_me(l_owner, l_name, l_lineno, l_caller_t)
-- who called me result seems empty when called from sql.
if l_owner is not null
then
raise;
else
return null;
end if;
end;
Of course : Hiding all errors is bad practise当然: 隐藏所有错误是不好的做法
Well, looking around I found that there is a hack available:好吧,环顾四周,我发现有一个 hack 可用:
The exception NO_DATA_FOUND isn't propagated when you call PL/SQL in SQL.
在 SQL 中调用 PL/SQL 时,不会传播异常NO_DATA_FOUND 。 So you can use this to "return null" instead of get an exception when calling it from SQL:
因此,当从 SQL 调用它时,您可以使用它来“返回空值”而不是获取异常:
create or replace function f return int as begin raise no_data_found; return 1; end f; / select f from dual; F null; declare v integer; begin v := f; end; Error report - ORA-01403: no data found
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.