SQL Server trigger to delete a single record from multiple tables

I know that this can be done using foreign keys, but I cannot add them or something strange when I insert new records. There are many stored procedures stored in this database, and I don’t know what they do, because I don’t know anything about stored procedures. I was hoping someone would help me deal with a trigger that will delete a specific ProductID when I remove it from the Product table. It is also located in tables called CompanyLink, TargetLink and CategoryLink.

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

+4
source share
1 answer

You can do this through a trigger as follows:

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 may not be perfect, but it's close to what you need.

+8
source

Source: https://habr.com/ru/post/952465/


All Articles