gpt4 book ai didi

SQL删除触发器

转载 作者:行者123 更新时间:2023-12-04 23:54:14 25 4
gpt4 key购买 nike

假设我有三个表:

表_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 中的相应行。

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

最佳答案

您的触发器将在稍作更正(删除拼写错误)后正常工作:

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

关于SQL删除触发器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com