我正在尝试创建一个基本数据库触发器,当从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
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
更好用:
DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key
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)
我建议使用
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
创建触发器示例触发器 ON 数据库1.dbo.table1 用于删除 作为 从database2.dbo.table2子表中删除 WHERE bar = 4 AND 存在(从已删除的 id 中选择 id,其中deleted.id = childTable.id) 去吧