当在select查询中调用function时,oracle不允许该function执行DML操作,而如果这个function被定义为自治事务,则不受此限制影响,如下测试
SQL> CREATE TABLE debug_output (msg VARCHAR2(200));
表已创建。
SQL> create or replace package debugging as
2 function log_msg(msg varchar2) return varchar2;
3 -- pragma restrict_references(log_msg,WNDS,RNDS);
4 END debugging;
5 /
程序包已创建。
SQL> create or replace package body debugging as
2 function log_msg(msg varchar2) return varchar2 is
3 -- pragma autonomous_transaction;
4 begin
5 insert into debug_output values(msg);
6 commit;
7 return msg;
8 end;
9 end debugging;
10 /
程序包体已创建。
SQL> select debugging.log_msg(ename) from emp where empno=9999;
select debugging.log_msg(ename) from emp where empno=9999
*
第 1 行出现错误:
ORA-14551: 无法在查询中执行 DML 操作
ORA-06512: 在 "SCOTT.DEBUGGING", line 5
执行查询时报错,无法在查询中执行DML操作,再将此function定义为自治事务:
SQL> create package debugging as
2 function log_msg(msg varchar2) return varchar2;
3 pragma restrict_references(log_msg,WNDS,RNDS);
4 END debugging;
5 /
程序包已创建。
SQL> create package body debugging as
2 function log_msg(msg varchar2) return varchar2 is
3 pragma autonomous_transaction;
4 begin
5 insert into debug_output values(msg);
6 commit;
7 return msg;
8 end;
9 end debugging;
10 /
程序包体已创建。
SQL> declare
2 my_emp_id number(6);
3 my_last_name varchar2(25);
4 my_count number;
5 begin
6 my_emp_id :=9999;
7 select debugging.log_msg(ename) into my_last_name from emp where empno=my_emp_id;
8 rollback;
9 end;
10 /
PL/SQL 过程已成功完成。
SQL> select * from debug_output;
MSG
--------------------------------------------------------------------------------
lsq
SQL> select debugging.log_msg(ename) from emp where empno=9999;
DEBUGGING.LOG_MSG(ENAME)
--------------------------------------------------------------------------------
lsq
SQL> select * from debug_output;
MSG
--------------------------------------------------------------------------------
lsq
lsq
可见每执行一次select查询,function都会执行一次,将数据插入到表debug_output中。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/10972173/viewspace-700050/ ,如需转载,请注明出处,否则将追究法律责任。