SQL Server ON DELETE触发器

时间:2012-04-03 15:35:44

标签: sql-server sql-server-2005 triggers

我正在尝试创建一个基本数据库触发器,当删除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

4 个答案:

答案 0 :(得分:58)

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

答案 1 :(得分:8)

最好使用:

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

答案 2 :(得分:2)

INSERTEDDELETED是虚拟表。它们需要在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 :(得分:1)

我建议使用exists代替in,因为在某些情况下暗示空值the behavior is different,所以

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