SQL Server 2008 - Multiple Cascading FK's - Do i need a trigger?

后端 未结 1 1910

I have a 1..* relationship between User and Post. (one user has many posts)

Post has a FK called \"UserId\", which

相关标签:
1条回答
  • 2021-01-13 14:08

    It's not a matter of which path will SQL Server choose, it does not allow it so that it won't wind up in a compromising position. When we ran into this situation, we had to resort to a trigger.

    1) As the error message stated, change the Users_PostHelpfuls FK to ON DELETE NO ACTION.

    2) Add an INSTEAD OF DELETE trigger to Users:

    CREATE TRIGGER dbo.Users_IO_Delete 
    ON dbo.Users
    INSTEAD OF DELETE
    AS
    BEGIN;
        DELETE FROM dbo.PostHelpfuls WHERE UserId IN (SELECT UserId FROM deleted);
    
        DELETE FROM dbo.Users WHERE UserId IN (SELECT UserId FROM deleted);
    END;
    

    Now, the FK will still enforce DRI, but the trigger is cascading the delete rather than the FK constraint.

    You could replace PostHelpfuls with Posts in the above steps. But when doing this it's best to use the trigger to remove the less independent entity's records. In other words, it's more likely that Posts are related to tables beside Users and PostHelpfuls than PostHelpfuls is related to tables beside Users and Posts.

    0 讨论(0)
提交回复
热议问题