使用PL/SQL删除百万条记录的大表:
最近开发人员对测试环境数据库进行了压力测试,数据库中产生了大量的脏数据。有几张大表里数据量均在百万甚至千万条的记录数。开发人员现提出需求如下:
只清理其中的部分脏数据,不允许对这些表使用truncate操作。于是就有了下面的PL/SQL清理脚本:
1.编写删除数据表数据的脚本内容如下:
$ cat data_del.sql
set serveroutput on
show serveroutput
DECLARE
V_LOGNUM NUMBER;
V_NEEDARC NUMBER;
BEGIN
SELECT count(1) INTO V_LOGNUM FROM V$LOG;
LOOP
LOOP
SELECT count(1) INTO V_NEEDARC FROM V$ARCHIVE;
IF V_NEEDARC < V_LOGNUM - 1 THEN
EXIT;
ELSE
DBMS_LOCK.SLEEP(60);
END IF;
END LOOP;
DELETE FROM T_USER.T_TABLE_NAME WHERE mobile='13800138000' AND rownum < 100;
IF SQL%ROWCOUNT = 0 THEN
EXIT;
END IF;
COMMIT;
END LOOP;
END;
/
show serveroutput
DECLARE
V_LOGNUM NUMBER;
V_NEEDARC NUMBER;
BEGIN
SELECT count(1) INTO V_LOGNUM FROM V$LOG;
LOOP
LOOP
SELECT count(1) INTO V_NEEDARC FROM V$ARCHIVE;
IF V_NEEDARC < V_LOGNUM - 1 THEN
EXIT;
ELSE
DBMS_LOCK.SLEEP(60);
END IF;
END LOOP;
DELETE FROM T_USER.T_TABLE_NAME WHERE mobile='13800138000' AND rownum < 100;
IF SQL%ROWCOUNT = 0 THEN
EXIT;
END IF;
COMMIT;
END LOOP;
END;
/
2.编写调用脚本:
$vim clear_dirt_data.sh
source ~/.bash_profile
sqlplus -s mytest/passwd@mydb