4

I have 3 table(Main, Detail, SubDetail) with cascade delete relation. also define AFTER Trigger on SubDetail for check some data.

SubDetail Trigger need to join Detail table for some data but in case of Delete Detail record, i can't access Detail record.

Example:

SELECT * 
FROM DELETED JOIN Detail on DELETED.DetailId = Detail.Id

How to access deleted record of Detail table in SubDetail Trigger???

UPDATE:

Why Table Hint does not work in my scenario? it must do all in one transaction

2
  • So if you delete from Detail table - it deletes from SubDetail then why not use after delete trigger on Details table that will get related data from SubDetail table?
    – gofr1
    Apr 18, 2016 at 10:45
  • you right but I not like do this because has many relation! By cascade delete I can ensure that not forgot write code for any relation!
    – Hamid
    Apr 18, 2016 at 16:39

1 Answer 1

1

Probably you can't join to Defail table because the record does not exist in Detail table because you try to join AFTER DELETE and you have cascade delete. You could do this by using trigger INSTEAD OF or remove cascade delete and delete related record in after trigger or change order of deleting tables

4
  • Why sql server does not delete all cascade record then delete self record??? Please note that i print text on subDetail trigger and it show first!!
    – Hamid
    Apr 18, 2016 at 16:33
  • I run some tests and this answer is right. Even if you will put deleted from details rows in some history table and will try to join them in subdetails after delete trigger - that will not get data you needed.
    – gofr1
    Apr 19, 2016 at 7:26
  • @Hamid it's about an order of execution, for example: when you type DELETE FROM MAIN WHERE ID=... then sql server delete all referenced table in this example Detail, after deleting Detail it will delete Main and after that it will execute after trigger on Detail and on Main Apr 19, 2016 at 8:17
  • I know, but if I raise error in AFTER TRIGGER (subDetail), all operation rollback, therefore i must access deleted item with table hint like: SELECT * FROM Detail WITH(READCOMMITTED)
    – Hamid
    Apr 19, 2016 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.