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 Detail 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)