I cannot seem to get my triggers to work as I expect, with me getting the error "Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <=, >, >= or when the subquery is used as an expression"
I have created several triggers that I use to achieve a cascading delete effect. I am using EF although I can't use it's Cascading Delete fuctionality as there are multiple delete paths in my database.
Anyway every time I delete a company and thus execute the DeleteCompany trigger, I get the above error. I have tried taking out some trigger which I believed to be the cause of the error but I get it every time.
Here are my triggers:
CREATE TRIGGER DeleteCompany
ON [dbo].[CompanySet]
INSTEAD OF DELETE
AS
DELETE FROM [dbo].[EmployeeSet]
WHERE CompanyId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[TemplateSet]
WHERE CompanyId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[SettingSet]
WHERE CompanyId = (SELECT Id FROM deleted) AND EmployeeId = NULL
DELETE FROM [dbo].[CustomerSet]
WHERE CompanyId = (SELECT Id FROM deleted)
GO
CREATE TRIGGER DeleteEmployee
ON [dbo].[EmployeeSet]
INSTEAD OF DELETE
AS
DELETE FROM [dbo].[SettingSet]
WHERE EmployeeId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[FavoriteSet]
WHERE EmployeeId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[ProjectEmployeeSet]
WHERE EmployeeId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[ActivityBaseSet]
WHERE EmployeeId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[ActivityReportSet]
WHERE EmployeeId = (SELECT Id FROM deleted)
GO
CREATE TRIGGER DeleteRole
ON [dbo].[RoleSet]
INSTEAD OF DELETE
AS
DELETE FROM [dbo].[AccountRoleSet]
WHERE RolesId = (SELECT Id FROM deleted)
GO
CREATE TRIGGER DeleteCustomer
ON [dbo].[CustomerSet]
INSTEAD OF DELETE
AS
DELETE FROM [dbo].[ProjectSet]
WHERE CustomerId = (SELECT Id FROM deleted)
GO
CREATE TRIGGER DeleteProject
ON [dbo].[ProjectSet]
INSTEAD OF DELETE
AS
DELETE FROM [dbo].[TemplateSet]
WHERE ProjectId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[ActivityBaseSet_Activity]
WHERE ProjectId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[ActivityReportSet]
WHERE ProjectId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[FavoriteSet]
WHERE ProjectId = (SELECT Id FROM deleted)
DELETE FROM [dbo].[ProjectEmployeeSet]
WHERE ProjectId = (SELECT Id FROM deleted)
GO
CREATE TRIGGER DeleteSettingDefinition
ON [dbo].[SettingDefinitionSet]
INSTEAD OF DELETE
AS
DELETE FROM [dbo].[SettingSet]
WHERE SettingDefinitionId = (SELECT Id FROM deleted)
GO
CREATE TRIGGER DeleteTemplate
ON [dbo].[TemplateSet]
INSTEAD OF DELETE
AS
UPDATE [dbo].[ActivityReportSet] SET [dbo].[ActivityReportSet].TemplateId = NULL
FROM deleted
WHERE [dbo].[ActivityReportSet].TemplateId = deleted.Id
GO
Am I missing something here?
Can you replace all your "=" with "IN" operator for your sub queries like:
DELETE FROM [dbo].[EmployeeSet]
WHERE CompanyId IN (SELECT Id FROM deleted)