ITPub博客

首页 > 数据库 > Oracle > PL/SQL程序中批量绑定时使用save exceptions记录错误数据

PL/SQL程序中批量绑定时使用save exceptions记录错误数据

原创 Oracle 作者:stotf 时间:2020-04-05 13:16:22 0 删除 编辑

一:利用scott下的emp表构造数据

--构造数据
Create Table t1 As Select * From scott.emp Where 1=2;
Alter Table t1 Add Constraint pk_emp_empno Primary Key(empno);
Alter Table t1 Modify(ename Not Null);
Alter Table t1 Add Constraint chk_sql check(Sal >= 800);
Create Table t2 As Select * FROM scott.emp;
Insert Into t2 Select * FROM scott.emp Where empno In(7369,7499);
Update t2 Set sal = 700 Where empno In(7521,7566);
Update t2 Set ename = Null Where empno = 7698;
Create Table t_error As Select * From scott.emp Where 1=2;
Alter Table t_error Add(error_idx number,ErrorCode Varchar2(50));

二:程序处理块

--一次获取所有ORA-24381错误的记录
Declare
  --定义ORA-24381对应的异常
  Excp_Bulk_Errors Exception;
  --将异常和错误号关联
  Pragma Exception_Init(Excp_Bulk_Errors, -24381);
  --定义存储Error Index和Error Code的变量
  n_Err_Idx      Number;
  Vc_Err_Code    Varchar2(50);
  Cur_Ref_Emp    Sys_Refcursor;
  Pi_Fetch_Limit Pls_Integer := 1000;
  Type Typ_Emp Is Table Of Emp%Rowtype Index By Binary_Integer;
  Typ_Emp_Rec Typ_Emp;
Begin
  Open Cur_Ref_Emp For
    Select * From T2;
  --批量获取
  Fetch Cur_Ref_Emp Bulk Collect
    Into Typ_Emp_Rec Limit Pi_Fetch_Limit;
  --批量执行
  Forall i In 1 .. Typ_Emp_Rec.Count Save Exceptions Execute Immediate
                   'insert into t1 values(:empno,:ename,:job,:mgr,:hiredate,:sal,:comm,:deptno)'
                   Using Typ_Emp_Rec(i).Empno, Typ_Emp_Rec(i).Ename, Typ_Emp_Rec(i).Job,
                         Typ_Emp_Rec(i).Mgr, Typ_Emp_Rec(i).Hiredate, Typ_Emp_Rec(i).Sal,
                         Typ_Emp_Rec(i).Sal, Typ_Emp_Rec(i).Deptno;
Exception
  When Excp_Bulk_Errors Then
    --清空错误日志表
    Execute Immediate 'delete from t_error';
    For i In 1 .. Sql%Bulk_Exceptions.Count() Loop
      n_Err_Idx   := Sql%Bulk_Exceptions(i).Error_Index;
      Vc_Err_Code := Sql%Bulk_Exceptions(i).Error_Code;
      Execute Immediate 'insert into t_error values(:empno,:ename,:job,:mgr,:hiredate,:sal,:comm,:deptno,:idx,:code)'
        Using Typ_Emp_Rec(n_Err_Idx).Empno, Typ_Emp_Rec(n_Err_Idx).Ename,
              Typ_Emp_Rec(n_Err_Idx).Job, Typ_Emp_Rec(n_Err_Idx).Mgr,
              Typ_Emp_Rec(n_Err_Idx).Hiredate, Typ_Emp_Rec(n_Err_Idx).Sal,
              Typ_Emp_Rec(n_Err_Idx).Sal, Typ_Emp_Rec(n_Err_Idx).Deptno,
              n_Err_Idx, Vc_Err_Code;
    End Loop;
End;

三:查看错误日志表结果

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31557103/viewspace-2684542/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2018-10-05

  • 博文量
    8
  • 访问量
    18252