简体   繁体   中英

Oracle ROWNUM with DELETE and Looping

Was wondering if someone can confirm the below delete statement for me as well as the loop I have setup, listed below. What I am trying to do is to delete records where the CREATED_DATE is older than 90 days BUT delete only 1k records at a time. If correct I plan to throw it into the loop which I've listed below. I've come across different results when using ROWNUM and just want to confirm.

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;

You probably want something like:

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;

EDIT:

I would rewrite your example as:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM