如何有条件的分步删除数据表中的记录[转帖]_MySQL, Oracle及数据库讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  MySQL, Oracle及数据库讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3996 | 回复: 0   主题: 如何有条件的分步删除数据表中的记录[转帖]        下一篇 
wayne
注册用户
等级:中校
经验:1690
发帖:221
精华:0
注册:2011-7-21
状态:离线
发送短消息息给wayne 加好友    发送短消息息给wayne 发消息
发表于: IP:您无权察看 2011-7-24 18:58:45 | [全部帖] [楼主帖] 楼主

有时候我们需要分配删除数据表的一些记录,分批提交以减少对于Undo的使用,本文提供一个简单的存储过程用于实现该逻辑。
你可以根据你的需要进行适当调整,本例仅供参考:

SQL> create table test as select * from dba_objects;

Table created.

SQL> create or replace procedure deleteTab
2 /**
3 ** Usage: run the script to create the proc deleteTab
4 ** in SQL*PLUS, type "exec deleteTab('Foo','ID>=1000000','3000');"
5 ** to delete the records in the table "Foo", commit per 3000 records.
6 ** Condition with default value '1=1' and default Commit batch is 10000.
7 **/
8 (
9 p_TableName in varchar2, -- The TableName which you want to delete from
10 p_Condition in varchar2 default '1=1', -- Delete condition, such as "id>=100000"
11 p_Count in varchar2 default '10000' -- Commit after delete How many records
12 )
13 as
14 pragma autonomous_transaction;
15 n_delete number:=0;
16 begin
17 while 1=1 loop
18 EXECUTE IMMEDIATE
19 'delete from '||p_TableName||' where '||p_Condition||' and rownum <= :rn'
20 USING p_Count;
21 if SQL%NOTFOUND then
22 exit;
23 else
24 n_delete:=n_delete + SQL%ROWCOUNT;
25 end if;
26 commit;
27 end loop;
28 commit;
29 DBMS_OUTPUT.PUT_LINE('Finished!');
30 DBMS_OUTPUT.PUT_LINE('Totally '||to_char(n_delete)||' records deleted!');
31 end;
32 /

Procedure created.

SQL> insert into test select * from dba_objects;

6374 rows created.

SQL> /

6374 rows created.

SQL> /

6374 rows created.

SQL> commit;

Commit complete.

SQL> exec deleteTab('TEST','object_id >0','3000')
Finished!
Totally 19107 records deleted!

PL/SQL procedure successfully completed.


很简单,但是想来也有人可以用到。

修正了一下,增加了2个缺省值,完整过程如下:

create or replace procedure deleteTab
(
p_TableName in varchar2, -- The TableName which you want to delete from
p_Condition in varchar2 default '1=1', -- Delete condition, such as "id>=100000"
p_Count in varchar2 default '10000' -- Commit after delete How many records
)
as
pragma autonomous_transaction;
n_delete number:=0;
begin
while 1=1 loop
EXECUTE IMMEDIATE
'delete from '||p_TableName||' where '||p_Condition||' and rownum <= :rn'
USING p_Count;
if SQL%NOTFOUND then
exit;
else
n_delete:=n_delete + SQL%ROWCOUNT;
end if;
commit;
end loop;
commit;
DBMS_OUTPUT.PUT_LINE('Finished!');
DBMS_OUTPUT.PUT_LINE('Totally '||to_char(n_delete)||' records deleted!');
end;
/




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论