如何处理异常并执行剩余语句?
Posted
技术标签:
【中文标题】如何处理异常并执行剩余语句?【英文标题】:How to handle exception and execute remaining statements? 【发布时间】:2013-06-28 07:42:21 【问题描述】:请找到下面的块。
for i in 1..acd.count loop
insert into customer_account_mapping select customerid,upper(pcd(i)),upper(acd(i)),cost from customer_master where customername=customer_name and concat(upper(pcd(i)),upper(acd(i))) not in (select concat(upper(pcode),upper(acode)) from customer_account_mapping);
insert into user_permissions select distinct user_id,sales_person_name,sales_mgr_name,upper(pcd(i)),upper(acd(i)) from user_permissions where sales_person_name=sales_person and concat(upper(pcd(i)),upper(acd(i))) not in (select concat(upper(pcode),upper(acode)) from user_permissions) and rownum<2 ;
commit;
end loop;
如果第一个插入语句发生错误如何处理并执行第二个插入语句。
【问题讨论】:
格式化你的代码会很有帮助,这样它就不会是一长行。 在每次插入后提交通常是不好的做法。为什么需要这样做? 【参考方案1】:用 begin ... end ... exception
换行,就像 try / catch
for i in 1..acd.count loop
begin
insert into customer_account_mapping select customerid,upper(pcd(i)),upper(acd(i)),cost from customer_master where customername=customer_name and concat(upper(pcd(i)),upper(acd(i))) not in (select concat(upper(pcode),upper(acode)) from customer_account_mapping);
exception when others then
-- handle the exception
end;
insert into user_permissions select distinct user_id,sales_person_name,sales_mgr_name,upper(pcd(i)),upper(acd(i)) from user_permissions where sales_person_name=sales_person and concat(upper(pcd(i)),upper(acd(i))) not in (select concat(upper(pcode),upper(acode)) from user_permissions) and rownum<2 ;
commit;
end loop;
【讨论】:
【参考方案2】:EXCEPTION -- exception handlers begin
WHEN exception type -- handles 'division by zero' error
...
WHEN OTHERS THEN -- handles all other errors
ROLLBACK;
END;
将此代码块放在第一个插入语句之后。
【讨论】:
以上是关于如何处理异常并执行剩余语句?的主要内容,如果未能解决你的问题,请参考以下文章