Oracle数据库Delete删除千万以上普通堆表数据的方法

2015-07-23 18:08:12 · 作者: · 浏览: 1

直接删除的影响:


1.可能由于undo表空间不足从而导致最终删除失败的问题;


2.可能导致undo表空间过度使用,影响到其他用户正常操作。


改进方案:每删除1k行就提交一次。(这样就把一个大事物拆分成了若干个小事物)


注意:下面方法以删除2014年之前的所有记录为例,请根据你的实际情况修改,防止误操作。


方法1


declare
? ? cursor [del_cursor] is select a.*, a.rowid row_id from [table_name] a order by a.rowid;
begin
? ? for v_cusor in [del_cursor] loop
? ? ? ? ? if v_cusor.[time_stamp] < to_date('2014-01-01','yyyy-mm-dd') then
? ? ? ? ? ? ? delete from [table_name] where rowid = v_cusor.row_id;
? ? ? ? ? end if;
? ? ? ? ? if mod([del_cursor]%rowcount,1000)=0 then
? ? ? ? ? ? ? commit;
? ? ? ? ? end if;
? ? end loop;
? ? commit;
end;


方法1中变量说明:


[del_cursor] 游标名


[table_name] 你要删除数据的表名


[time_stamp] 你用作过滤条件的表的时间字段名称


方法2


declare?
maxrows number default 1000;
delete_ct number default 0;
begin
select count(1)/maxrows? into delete_ct from [table_name] where [time_stamp] < to_date('2014-01-01','yyyy-mm-dd');
for i in 1..TRUNC(delete_ct)+1
loop
delete [table_name] where [time_stamp] < to_date('2014-01-01','yyyy-mm-dd') and rownum <= maxrows;
commit;
end loop ;
end;


方法2中变量说明:


[table_name] 你要删除数据的表名


[time_stamp] 你用作过滤条件的表的时间字段名称


Note


两种方法的核心的思路都是把一个大事物拆分成了若干个小事物,无论采用哪种方法,都建议先在对应的测试环境中测试后再考虑是否可以在实际生产使用。


顺便说一句,这样的大表应该要综合考虑下是否可以改造成分区表。