这里我们只是在90天历史记录之前删除主表和子表中的记录。假设表中有超过20k的记录可供删除。在这里,我为每个5k记录提交了提交。如果我在这里错了,请告诉我?
create or replace Procedure PURGE_CLE_ALL_STATUS ( days_in IN number )
IS
reccount NUMBER := 0;
CURSOR del_record_cur IS
SELECT EXCEPTIONID FROM EXCEPTIONREC
WHERE trunc(TIME_STAMP) < trunc(sysdate - days_in );
BEGIN
FOR rec IN del_record_cur LOOP
delete from EXCEPTIONRECALTKEY -- child table
where EXCEPTIONID =rec.EXCEPTIONID ;
delete from EXCEPTIONREC -- master table
where EXCEPTIONID =rec.EXCEPTIONID;
reccount := reccount + 1;
IF (reccount >= 1000) THEN
COMMIT;
count := 0;
END IF;
commit;
END LOOP;
COMMIT;
DBMS_OUTPUT.PUT_LINE('Deleted ' || total || ' records from <OWNER>.<TABLE_NAME>.');
END;
/
答案 0 :(得分:5)
如果您在询问是否可以提高代码效率,最有效的方法始终是在SQL中执行操作
BEGIN
DELETE FROM EXCEPTIONRECALTKEY child
WHERE EXISTS( SELECT 1
FROM EXCEPTIONREC parent
WHERE child.EXCEPTIONID = parent.EXCEPTIONID
AND parent.timestamp <= trunc(sysdate - days_in ) );
DELETE FROM EXCEPTIONREC
WHERE timestamp <= trunc(sysdate - days_in );
END;
答案 1 :(得分:2)
如果您有从EXCEPTIONRECALTKEY到EXCEPTIONREC定义的外键,那么您可以对连接两个表的内联视图发出删除,为父表指定WHERE子句并导致从子表中删除记录。 / p>
因此:
BEGIN
delete from (
select
p.EXCEPTIONID p_EXCEPTIONID,
c.EXCEPTIONID c_EXCEPTIONID,
c.TIME_STAMP c_TIME_STAMP
from
EXCEPTIONREC p,
EXCEPTIONRECALTKEY c
where
p.EXCEPTIONID = c.EXCEPTIONID and
c.TIMESTMAP < trunc(sysdate - days_in ));
delete from
EXCEPTIONREC
where
TIMESTMAP < trunc(sysdate - days_in );
end;
/