ORACLE SAVE EXCEPTION 子句

来源:互联网 发布:大连软件职业学院学费 编辑:程序博客网 时间:2024/05/22 05:28

今天在一个帖子里看到shiyiwan的回帖中提及到了两个自己以前没见过的概念,save exception和dml error logging。上网搜了搜相关内容,看了看大概明白意思,不过在实际运用中还是没怎么用过。保存下来,以后用的到的话方便查阅。

这一篇是关于save exception的,另外一篇dml error logging的参见如下链接

http://blog.csdn.net/wh62592855/archive/2009/11/13/4808012.aspx

 

==================================================================================

 

Oracle 从9i 开始增强了批 DML 在发生异常时处理的错误及失败的程序执行能力。这是通过FORALL 语句的 SAVE EXCEPTION 子句来实现,其语法如下:

FORALL index in lower..upper save exceptions

SAVE EXCEPTIONS 子句是 oracle 9i 中引入的,它在一个隐式游标属性,SQL%BULK_EXCEPTIONS 中保存错误行,允许 FORALL 语句继续处理其余行。

下面这一段代码是 SQL%BULK_EXCEPTIONS 的应用例子:

 

create or replace procedure batch_dml(errnum outnumber,errtext outvarchar2)
is


type user_id_tab is table of number index by binary_integer;
type user_name_tab is table of varchar2( 20 ) index by binary_integer;
type user_sex_tab is table of varchar2( 2 ) index by binary_integer;
 
user_id user_id_tab;
user_name user_name_tab;
user_sex user_sex_tab;

bulk_bind_excep EXCEPTION;
pragma exception_init(bulk_bind_excep,- 24381 );
begin
for idx in 1 .. 50000 loop

user_id(idx):=idx;
user_name(idx):= 'xxx' ||idx;
user_sex(idx):= 'F' ;
endloop;
user_id( 40000 ):= 39999 ;
user_id( 10000 ):= 9999 ;
delete from t_user;
forall idx in user_id.first..user_id.last save exceptions
insert into t_user values(user_id(idx), user_name(idx),user_sex(idx));
errnum:= 0 ;
errtext:= '' ;
exception
when bulk_bind_excep then
for i in 1 ..sql%bulk_exceptions.count loop
dbms_output.put_line( 'Iteration '
||SQL%bulk_exceptions(i).error_index|| 'failed with error '
||sqlerrm(sql%bulk_exceptions(i).error_code));
endloop;
commit;
when others then
commit;
errnum:=sqlcode;
errtext:=sqlerrm;
end batch_dml;


这个例子是修改了上面的程序,加上 save exceptions 异常处理,当批 dml发生异常时也能正常运行。