SQL Server ON DELETE 触发器

问题描述 投票:0回答:5

我正在尝试创建一个基本数据库触发器,当从database2.table2 中删除行时,该触发器有条件地从database1.table1 中删除行。我是触发器新手,希望学习实现此目标的最佳方法。这是我到目前为止所拥有的。有建议吗?

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    IF EXISTS (SELECT foo
               FROM database2.dbo.table2
               WHERE id = deleted.id
               AND bar = 4)

-- If there is a row that exists in database2.dbo.table2 
-- matching the id of the deleted row and bar=4, delete 
-- it as well.

-- DELETE STATEMENT?

GO
sql-server sql-server-2005 triggers
5个回答
68
投票
CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    DELETE FROM database2.dbo.table2
    WHERE bar = 4 AND ID IN(SELECT deleted.id FROM deleted)
GO

10
投票

更好用:

DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key

3
投票

INSERTED
DELETED
是虚拟表。它们需要在
FROM
子句中使用。

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    IF EXISTS (SELECT foo
               FROM database2.dbo.table2
               WHERE id IN (SELECT deleted.id FROM deleted)
               AND bar = 4)

3
投票

我建议使用

exists
而不是
in
因为在某些情况下暗示空值行为不同,所以

CREATE TRIGGER sampleTrigger
    ON database1.dbo.table1
    FOR DELETE
AS
    DELETE FROM database2.dbo.table2 childTable
    WHERE bar = 4 AND exists (SELECT id FROM deleted where deleted.id = childTable.id)
GO

0
投票

创建触发器示例触发器 ON 数据库1.dbo.table1 用于删除 作为 从database2.dbo.table2子表中删除 WHERE bar = 4 AND 存在(从已删除的 id 中选择 id,其中deleted.id = childTable.id) 去吧

© www.soinside.com 2019 - 2024. All rights reserved.