触发器会导致其他触发器执行吗?

Do triggers cause other triggers to execute?

我对 TSQL 中的触发器有疑问。

假设我有 3 个表:

Companies
---------
Id

Employees
---------
Id
CompanyId

Tasks
-----
EmployeeId

现在我为前 2 个表 CompaniesEmployees 创建了 2 个触发器:

CREATE TRIGGER DeleteCompany
    ON [dbo].[Companies]
    INSTEAD OF DELETE
AS
    DELETE FROM [dbo].[Employees]
    WHERE CompanyId IN (SELECT Id FROM deleted)     
GO

CREATE TRIGGER DeleteEmployee
    ON [dbo].[Employees]
    INSTEAD OF DELETE
AS
    DELETE FROM [dbo].[Tasks]
    WHERE EmployeeId IN (SELECT Id FROM deleted)        
GO

到目前为止一切顺利。现在,如果我删除一家公司,触发器 DeleteCompany 将被执行,映射的 Employees 将被删除。我的问题是,这会导致触发器 DeleteEmployee 执行吗?因为我基本上是想这样做,但只执行了第一个触发器 (DeleteCompany)。

好的,我找到问题了。我对 INSTEAD OF 的实际作用感到有点困惑。事实证明,它完全取代了 DELETE,所以我不得不在删除它的引用后删除实际记录,如下所示:

CREATE TRIGGER DeleteCompany
    ON [dbo].[Companies]
    INSTEAD OF DELETE
AS
    DELETE FROM [dbo].[Employees]
    WHERE CompanyId IN (SELECT Id FROM deleted)  

    DELETE [dbo].[Companies] WHERE [dbo].[Companies].Id IN (SELECT Id FROM deleted)   
GO

CREATE TRIGGER DeleteEmployee
    ON [dbo].[Employees]
    INSTEAD OF DELETE
AS
    DELETE FROM [dbo].[Tasks]
    WHERE EmployeeId IN (SELECT Id FROM deleted) 

    DELETE [dbo].[Employees] WHERE [dbo].[Employees].Id IN (SELECT Id FROM deleted)            
GO

这样就达到了预期的级联删除效果。

这是 post 让我意识到这一点的原因:Link