When using the delete statement to delete data, the database needs to log records so that the data can be recovered in the future, but when I delete millions of data, it is very slow or even crashes. Is there any good way? [@more@]
Netizen's point of view 1:
create or replace procedure delete_table
is
i number(10);
begin
for x in (select * from emp where DEPTNO like 'a%')
loop
delete emp where emp.id = x.id
i:=i+1;
if i>1000 then
commit;
i:=0;
end if;
end loop;
exception
when others then
dbms_out.put_line(sqlcode);
rollback;
end delete_table;
Netizen's point of view 2:
This is what I usually use to delete data in batches and submit every 500 pieces of data.
DECLARE
CNT NUMBER(10):=0;
I NUMBER(10);
BEGIN
SELECT COUNT(*) INTO CNT FROM ep_arrearage_bak WHERE TO_CHAR(DF_DATE,'MM')='01';
FOR I IN 1..TRUNC(CNT/500)+1 LOOP
DELETE FROM ep_arrearage_bak WHERE TO_CHAR(DF_DATE,'MM')='01' AND ROWNUM<=500;
COMMIT;
END LOOP;
END;
Expert opinion: Several ways:
1. If the deleted data is most of the data, it is recommended to use the method upstairs to put the data to be retained in a temporary table, truncate the table and then put it back
2. It can also be submitted in sections, which is also mentioned upstairs
3. Dedicated use of a large rollback segment
4. If you confirm that you do not need to restore in the future, change to non-archive mode, delete it and change it back and make a backup.
Solutions from experts:
Conditionally delete records in the data table step by step
-- create a test table
create table test as select * from dba_objects;
Table created. --Create
a stored procedure to delete a table
create or replace procedure deleteTab --Insert
statement
SQL> insert into test select * from dba_objects;
6374 rows created.
SQL> /
6374 rows created.
SQL> /
6374 rows created.
SQL> commit;
--创建删除的存储过程
create or replace procedure deleteTab
/**
** Usage: run the script to create the proc deleteTab
** in SQL*PLUS, type "exec deleteTab('Foo','ID>=1000000','3000');"
** to delete the records in the table "Foo", commit per 3000 records.
** Condition with default value '1=1' and default Commit batch is 10000.
**/
(
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;
/
--Execute the statement
SQL> exec deleteTab('TEST','object_id >0','10000')
You can see the execution result. I have tried it, and the effect is OK