微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL程序中批量绑定时怎么使用save exceptions记录错误数据

这篇文章主要讲解了“Postgresql程序中批量绑定时怎么使用save exceptions记录错误数据”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Postgresql程序中批量绑定时怎么使用save exceptions记录错误数据”吧!

一:利用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;

感谢各位的阅读,以上就是“Postgresql程序中批量绑定时怎么使用save exceptions记录错误数据”的内容了,经过本文的学习后,相信大家对Postgresql程序中批量绑定时怎么使用save exceptions记录错误数据这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是编程之家,小编将为大家推送更多相关知识点的文章,欢迎关注!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐