I have a question regarding triggers in TSQL.
Let's say I have 3 tables:
Companies
---------
Id
Employees
---------
Id
CompanyId
Tasks
-----
EmployeeId
Now I create 2 triggers for the top 2 tables Companies
and Employees
:
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
So far so good. Now, if I delete a company, the trigger DeleteCompany
will be executed and the mapped Employees
will be removed. My question is, will this cause the trigger DeleteEmployee
to execute? Because I am trying to basically do this but only the first trigger (DeleteCompany) is executed.
OK I have found the problem. I was a little confused about what INSTEAD OF
actually does. It turns out, it completely replaces the DELETE so I had to delete the actual record after I deleted it's references like so:
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
This does the trick and the desired cascading delete effect is achieved.
This is the post that led me to this realization: Link