温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-11-04 17:15:58 来源:亿速云 阅读:144 作者:iii 栏目:关系型数据库

这篇文章主要讲解了“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记录错误数据这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI