1

我有一张Absence带 PK的桌子AbscenceId(是的拼写错误)。我有另一个 table Note,带有一个 FK intoAbsence调用AbsenceId(这次拼写正确)。FK 约束为:

ALTER TABLE [dbo].[Note]  WITH CHECK ADD  CONSTRAINT [FK_Note_Absence] FOREIGN KEY([AbsenceId])
REFERENCES [dbo].[Absence] ([AbscenceId])
GO

当 anAbsence被删除时,我希望所有人都Notes可以使用它。我不能这样做CASCADES,因为 aNote也可以属于其他东西。

所以我创建了一个触发器来在删除缺席时删除笔记:

ALTER TRIGGER [dbo].[TR_OnAbsenceDelete] ON [dbo].[Absence]
    FOR DELETE AS

    DELETE FROM [Note]
        WHERE AbsenceId IN ( SELECT AbscenceId FROM Deleted )

但是当我删除Absence一个Note附加的,我得到:

Msg 547, Level 16, State 0, Line 1
The DELETE statement conflicted with the REFERENCE constraint "FK_Note_Absence". The conflict occurred in database "ReturnToWork", table "dbo.Note", column 'AbsenceId'.
The statement has been terminated.�

这几乎就像触发器没有被执行?

4

2 回答 2

3

您的触发器需要编写为 INSTEAD OF 触发器,首先从 Note 中删除,然后从 Absence 中删除。

CREATE TRIGGER [dbo].[TR_OnAbsenceDelete] ON [dbo].[Absence]
    INSTEAD OF DELETE AS
BEGIN

    DELETE FROM n
        FROM deleted d
            INNER JOIN Note n
                ON d.AbscenceId = n.AbsenceId

    DELETE FROM a
        FROM deleted d
            INNER JOIN Absence a
                ON d.AbscenceId = a.AbscenceId
END
于 2012-07-17T20:22:22.273 回答
1

问题是当您尝试从缺席中删除记录时,由于引用约束而失败。如果删除成功,则将调用您的删除触发器。

此外,正如此链接中所建议的那样,您可以尝试在 T-SQL 2005 中删除之前如何触发触发器而不是如何触发触发器?

于 2012-07-17T20:12:42.103 回答