Jamie
Jamie

Reputation: 1679

SQL Server Trigger to DELETE one record from multiple tables

I know this can be done with foreign keys but I cannot add them or something weird happens when I am inserting new records. There are a lot of stored procedures in this database and I don't know what they do since I know nothing about stored procedures. I was hoping someone could help me figure out a trigger that will delete a specific ProductID when I delete it from the Product table. It is also located in tables called CompanyLink, TargetLink, and CategoryLink.

As of right now, when I delete the ProductID from the Product table, I have to manually delete it from the other 3 tables it was inserted into.

Upvotes: 4

Views: 11847

Answers (1)

James Johnson
James Johnson

Reputation: 46047

You can do it through a trigger like this:

CREATE TRIGGER [dbo].[ProductDeleted]
ON [dbo].[Product]
AFTER DELETE
AS
BEGIN

   DELETE FROM CompanyLink WHERE ProductID = (SELECT TOP 1 ProductID FROM DELETED)
   DELETE FROM TargetLink WHERE ProductID = (SELECT TOP 1 ProductID FROM DELETED)

END 

Obviously the syntax might not be perfect, but this is close to what you need.

Upvotes: 7

Related Questions