3

假设我有三个表:

表格1:

 ID     INT     PRIMARY
 name NVARCHAR

表_2:

ID         INT    PRIMARY
Table_1_ID INT (foreign key)

表3:

ID         INT    PRIMARY
Table_2_ID INT (foreign key)

前两个表具有以下触发器:

-- Table_1
CREATE TRIGGER tr_1
ON Table_1
INSTEAD OF DELETE
AS
BEGIN
    DELETE FROM Table_2
    WHERE Table_1_ID IN (SELECT deleted.ID FROM Table_1)

    DELETE FROM Table_1
    WHERE ID IN (SELECT deleted.ID FROM deleted)
END

-- Table_2
CREATE TRIGGER sr_bf_trigger_delete_ID
ON Table_2
INSTEAD OF DELETE
AS
BEGIN
    DELETE FROM Table_3
    WHERE Table_2_ID IN (SELECT deleted.ID FROM deleted)

    DELETE FROM Table_2
    WHERE ID IN (SELECT deleted.ID FROM deleted)
END

这个想法是,一旦我删除了 中的一行(或多行)Table_1,它将启动触发器并删除 中的相应行Table_2。但是,在删除 中的行之前,会删除 中的Table_2相应行Table_3

这行得通吗?我看到的可能问题是我两次访问同一个“已删除”表。

4

1 回答 1

0

您的触发器将在较小的更正下正常工作(删除错别字):

CREATE TRIGGER tr_1
ON Table_1
INSTEAD OF DELETE
AS
BEGIN
    DELETE FROM Table_2
    WHERE Table_1_ID IN (SELECT d.ID FROM deleted as d)

    DELETE FROM Table_1
    WHERE ID IN (SELECT d.ID FROM deleted as d)
END;

-- Table_2
CREATE TRIGGER sr_bf_trigger_delete_ID
ON Table_2
INSTEAD OF DELETE
AS
BEGIN
    DELETE FROM Table_3
    WHERE Table_2_ID IN (SELECT d.ID FROM deleted as d)

    DELETE FROM Table_2
    WHERE ID IN (SELECT d.ID FROM deleted as d)
END;

sql fiddle demo

于 2013-09-08T11:57:39.390 回答