Need help with a trigger

  • I need some help with a trigger. In general I try not to use triggers, but this time, it seems to make sense.

    Basically what I have is a table (T1) with a foreign key (to T2). When I delete from T1, I want the corresponding entry in T2 to also be deleted. So far that is easy. Where I am finding difficulty is that multiple rows in T1 can have the same foreign key to T2. So in my trigger, I only want the entries in T2 to be deleted if there are no remaining foreign keys in T1 referencing it. Any ideas on how I can solve this?

    I don't mind doing the leg work on researching this, but whenever I search these forums (or google) for "Triggers", I get way more results than I can possibly sort through quickly. The articles I have read so far have not helped me out. If anyone knows of a good article that can point me in the right direction with this issue, that would be greatly appreciated as well.

    Thanks for any help.

    -Justin

  • I would think just add a step in your trigger to count the id's in T1 if the count is 0 then delete fro t2

    Dan

    If only I could snap my figures and have all the correct indexes apear and the buffer clean and.... Start day dream here.

  • if you setup the foreign key to cascade deletes, then you won't need the overhead of a trigger. It will handle multiple deletes and you will never have orphan records

    For better, quicker answers, click on the following...
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

    For better answers on performance questions, click on the following...
    http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply