带有DELETE和循环的Oracle ROWNUM

时间:2017-10-10 16:14:32

标签: sql oracle plsql

想知道是否有人可以为我确认以下删除声明以及我已设置的循环,如下所示。我想要做的是删除CREATED_DATE早于90天的记录但是一次只删除1k条记录。如果正确的话,我打算将它放入我在下面列出的循环中。我在使用ROWNUM时遇到了不同的结果,只是想确认一下。

DELETE from
(select * from ESPADMIN.ESP_STATUS_MESSAGE where CREATED_DATE <SYSDATE-90)
WHERE ROWNUM <1001 ;
commit;


LOOP
DELETE from
(select * from ESPADMIN.ESP_STATUS_MESSAGE where CREATED_DATE <SYSDATE-90)
WHERE ROWNUM <1001 ;
commit;
END LOOP;

1 个答案:

答案 0 :(得分:1)

您可能需要以下内容:

DECLARE 
  cnt INT;
BEGIN
  SELECT COUNT(*)    -- 0/1
  INTO cnt
  FROM dual
  WHERE EXISTS (SELECT 1 
               FROM ESPADMIN.ESP_STATUS_MESSAGE 
               where CREATED_DATE <SYSDATE-90);

  WHILE (cnt > 0) LOOP
    DELETE ESPADMIN.ESP_STATUS_MESSAGE 
    where CREATED_DATE <SYSDATE-90
      AND rownum < 1001;

    COMMIT;

    SELECT COUNT(*)
    INTO cnt
    FROM dual
    WHERE EXISTS (SELECT 1 
                  FROM ESPADMIN.ESP_STATUS_MESSAGE 
                  where CREATED_DATE <SYSDATE-90);
  END LOOP;
END;

修改

我会将你的例子重写为:

BEGIN
LOOP 
  DELETE from (select * 
               from ESPADMIN.ESP_STATUS_MESSAGE where CREATED_DATE <SYSDATE-90) 
  WHERE ROWNUM <1001 ;
  EXIT WHEN sql%ROWCOUNT = 0;
  commit;
END LOOP;
COMMIT;
END;