oracle 对表中的记录进行大批量删除

本文介绍在Oracle数据库中如何通过分批删除和逐次提交的方法来高效处理大批量数据删除任务。这种方法可以有效减少对其他事务的影响,避免锁等待,并减轻临时表空间的压力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
for i in 1..ceil(icount/irownum) loop
    delete from  tb_detail a
    where  createdate and rownum<=n_rownum ;
    commit;
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;

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

转载于:http://blog.itpub.net/28539951/viewspace-1417272/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值