时间:2021-07-01 10:21:17 帮助过:33人阅读
Oracle 对表中的记录进行大批量删除数量时,常常采用分批删除,逐次提交.其目的大概有三个原因:
Oracle 对表中的记录进行大批量删除数量时,常常采用分批删除,逐次提交.其目的大概有三个原因:
1.避免对其他事务select的影响
如果其他事务有需要查询这些要删除的记录,就需要去undo段查询前映像.分批逐次可以减少行更新的时间,以减少这种情况的发生.
2.避免各事务dml的锁等待
如果要删除的这些记录上,有其他事务在做dml操作,就可能会产生相互的行锁等待.分批逐次可以减少行锁定的时间,以减少这种情况的发生.
3.减少使用临时表空间对性能产生的影响
在关联删除时,可能会用到sort或hash区,一次对大量记录进行操作,如果sort_area_size或hash_area_size大小不够就会使用临时表空间,性能会降低.分批逐次可以减少单次操作的记录数,以减少这种情况的发生.
以下是一些对大批量删除进行分批删除逐次提交的代码,可根据自己的实际情况测试修改后实施.
--对无关联的单表中的记录按条件删除
declare
n_count number;
n_rownum number:=10000;
begin
select count(*) into n_count from tb_detail where createdate
delete from tb_detail a
where createdate
end loop;
end;
--对有关联的表按条件删除
declare
type ridArray is table of rowid index by binary_integer;
type dtArray is table of varchar2(50) index by binary_integer;
v_rowid ridArray;
v_fid_to_delete dtArray;
n_delete number;
n_rownum number:=10000;
begin
select count(*)
into n_delete
from tb_main
where createdate < to_date('20140101', 'yyyymmdd');
for i in 1 .. ceil(n_delete / n_rownum) loop
select fid, rowid BULK COLLECT
INTO v_fid_to_delete, v_rowid
from tb_main
where createdate < to_date('20140101', 'yyyymmdd')
and rownum <= n_rownum;
forall j in 1 .. v_fid_to_delete.COUNT
delete from tb_detail where fid = v_fid_to_delete(j);
forall k in 1 .. v_rowid.COUNT
delete from tb_main where rowid = v_rowid(k);
commit;
end loop;
end;
--对有关联的表按条件删除子表或主表
declare
type dtArray is table of varchar2(50) index by binary_integer;
v_fid_to_delete dtArray;
n_delete number;
n_rownum number := 10000;
begin
select fid BULK COLLECT
INTO v_fid_to_delete
from tb_main
where createdate < to_date('20140601', 'yyyymmdd');
for i in 1 .. ceil(v_fid_to_delete.COUNT / n_rownum) loop
forall j in (i - 1) * n_rownum + 1 .. least(i * n_rownum,v_fid_to_delete.COUNT)
delete from tb_detail where fid = v_fid_to_delete(j);
commit;
end loop;
end;
本文永久更新链接地址:
,