-1

在这里,我们只是从主表和子表中删除 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;
/
4

2 回答 2

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;
于 2012-05-21T03:24:57.360 回答
2

如果您有一个从 EXCEPTIONRECALTKEY 到 EXCEPTIONREC 定义的外键,那么您可以对连接两个表的内联视图发出删除操作,对父表指定 WHERE 子句并导致从子表中删除记录。

因此:

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;
/
于 2012-05-21T11:29:11.407 回答