SQL Server:是否可以级联更新自引用表?

时间:2010-12-03 16:58:18

标签: sql-server

看来,至少通过管理工作室表示,不可能设置引用同一个表的外键约束来执行更新或删除操作。 我有一个表,如果删除一行,我想将更新级联为null。

这可能吗?

谢谢,

1 个答案:

答案 0 :(得分:2)

您需要使用INSTEAD OF DELETE触发器来处理这种情况。

类似的东西:

CREATE TRIGGER tr_IOD_YourTable ON YourTable
INSTEAD OF DELETE
AS
BEGIN
    SET NOCOUNT ON

    UPDATE yt
        SET ChildForeignKey = NULL
        FROM deleted d
            INNER JOIN YourTable yt
                ON d.PrimaryKeyColumn = yt.ChildForeignKey

    DELETE FROM yt
        FROM deleted d
            INNER JOIN YourTable yt
                ON d.PrimaryKeyColumn = yt.PrimaryKeyColumn
END