2

标识符上有三个一一对应的表。我需要删除三个表中符合条件 A.ID = B.ID = C.ID 的所有记录

现在我按以下方式进行:

DECLARE
    CURSOR CUR IS 
        SELECT C.ID FROM A 
        INNER JOIN B ON A."ID" = B."ID" 
        INNER JOIN C ON B."ID" = C."ID"
        WHERE A.STATUS = 'ERROR';
    IDX NUMBER;
BEGIN
    FOR REC IN CUR LOOP 
        IDX := REC.ID;
        DELETE FROM C WHERE C."ID" = IDX;
        DELETE FROM B WHERE B."ID" = IDX;
        DELETE FROM A WHERE BP."ID" = IDX;
    END LOOP;
    COMMIT;
END;

大量数据,这种方式可以长期运行。有什么方法可以更快的删除吗?

4

1 回答 1

3

您可以创建一个 PL/SQL 类型来存储 ID。

CREATE TYPE t_ids AS TABLE OF NUMBER;

从表中删除所有a符合条件的记录,并将 ID 返回到该类型的变量中。b然后从c这些 ID 中删除所有记录。

DECLARE
  ids_to_delete   t_ids;
BEGIN
  DELETE FROM a
   WHERE a.status = 'ERROR'
     AND EXISTS ( SELECT 1 FROM b WHERE b.id = a.id )
     AND EXISTS ( SELECT 1 FROM c WHERE c.id = a.id )
  RETURNING a.id
  BULK COLLECT INTO ids_to_delete;

  DELETE FROM b
   WHERE id IN ( SELECT COLUMN_VALUE FROM TABLE( ids_to_delete ) );

  DELETE FROM c
   WHERE id IN ( SELECT COLUMN_VALUE FROM TABLE( ids_to_delete ) );
END;

这应该会执行得更好,因为它不需要循环并且在三个 SQL 语句中完成所有事情,而不是每个 ID 三个语句。

于 2012-10-30T09:10:34.323 回答