从多个相关表中删除行

时间:2012-10-30 05:27:25

标签: sql oracle plsql oracle10g cascading-deletes

标识符上有三个与一对一相关的表。我需要删除符合条件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;

很多数据和这种方式很长时间运行。有没有办法快速删除?

1 个答案:

答案 0 :(得分:3)

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

CREATE TYPE t_ids AS TABLE OF NUMBER;

删除表a中与标准匹配的所有记录,并将ID返回到该类型的变量中。然后使用这些ID删除bc中的所有记录。

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执行三个语句。