开发者

How to retrieve data in a trigger from the header table that was already deleted

I have a situation where I have a Header and a Detail table. The Detail table has a foreign key relationship to the Header table with Cascade delete.

When the detail records are deleted I need to update other tables using a trigger. The problem I am having is that I need to pull some information from the Header table as well as the Detail table for the deleted records. If I delete the Detail records and then the Header record the trigger appears to run fine. However, if I delete the Header record, which in turn deletes the Detai开发者_如何学Pythonl records due to the cascading delete, then when the trigger executes the Header record is already deleted and I can't access the information I need from it.

I am rather new to triggers, so I'm wondering if there is something I just don't know and how I accomplish this.

Here is my code:

ALTER TRIGGER [Detail_Delete]
   ON [Detail]
   AFTER DELETE
AS 
BEGIN
 SET NOCOUNT ON;

 DECLARE @Table UpdateTableType

 -- Here is where the problem lies.
 -- No records are found here because the Header record isn't found.
 INSERT @Table
 (HeaderID, UserID)
 SELECT d.HeaderID, h.UserID
 FROM deleted d
 JOIN Header h ON h.HeaderID = d.HeaderID

 EXECUTE sp_UpdateSummary
  @Table = @Table
END


I wouldn't use a cascade delete because as you've seen, the deleted parent data isn't available

A stored procedure is ideal for this. If not for whatever reason, you can use a BEFORE trigger on the Header table to do the Detail and other deletes (and of course the Header table)

ALTER TRIGGER [Header_Delete]
   ON [Header]
   INSTEAD OF DELETE
AS 
BEGIN
 SET NOCOUNT ON;

 DECLARE @Table UpdateTableType

 -- DELETED has data, even though Header has not yet been touched
 INSERT @Table
 (HeaderID, UserID)
 SELECT d.HeaderID, d.UserID
 FROM deleted

 DELETE Detail WHERE ... (using @Table)

 DELETE Other WHERE ... (using @Table)

 DELETE Header WHERE ... (using @Table)

 EXECUTE sp_UpdateSummary
  @Table = @Table ...
END


If the Header record is deleted first, you have no access to it when the Detail-Record trigger runs as the Header records are already deleted.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜