开发者

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 ta开发者_Go百科ble, I have to manually delete it from the other 3 tables it was inserted into.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜