如何实现SQL Server触发器作为ON DELETE CASCADE的替代?

时间:2017-01-15 22:49:33

标签: sql-server triggers sql-server-2016

我想在SQL Server 2016中使用时态表。目前,时态表不允许使用ON DELETE CASCADE。如何实现触发器来模仿行为?我想保留外键,因为我在我的应用程序中使用了Entity Framework的导航属性。

我认为后触发器不起作用,因为delete语句不适用于外键条件。

假设我们有以下简单的情况:

enter image description here

  1. UserRole.UserId:User.Id的外键
  2. UserRole.RoleId:Role.Id的外键
  3. 如果我删除Id == 2的角色,而不是删除UserRole中的第二和第四行。如何在没有时间表中的ON DELETE CASCADE的情况下实现这一点?

1 个答案:

答案 0 :(得分:1)

就像我在评论部分提到的那样,你需要一个Instead of Trigger,就像这样......

CREATE TRIGGER tr_CascadeDelete_UserRole
ON [Role]
INSTEAD OF DELETE
AS
BEGIN
  SET NOCOUNT ON;

  --** Delete Rows from [UserRole] table first 
  DELETE FROM [UserRole]
  WHERE EXISTS (SELECT 1 
                FROM Deleted d
                WHERE d.RoleID = [UserRole].RoleID)

  --** Delete Rows from [Role] table first 
  DELETE FROM [Role]
  WHERE EXISTS (SELECT 1 
                FROM Deleted d
                WHERE d.RoleID = [Role].RoleID)

END