我对TSQL中的触发器有疑问。
我们说我有3张桌子:
Companies
---------
Id
Employees
---------
Id
CompanyId
Tasks
-----
EmployeeId
现在我为前2个表格Companies
和Employees
创建了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)。
答案 0 :(得分:0)
好的,我发现了问题。我对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
这样做可以实现所需的级联删除效果。
这是让我意识到这一点的帖子:Link