trigger to delete FK and PK

  • HI...

    I have a simple example:

    table 1

    id int -> primary key

    table2

    id int -> foreign key of table1.id

    example data:

    table 1

    1

    2

    3

    4

    table 2

    2

    3

    Question:

    * which table should I create trigger??

    * if I'll create trigger in table2, how can I delete item from table1 if there is no the same id in table2??

    I really need simple SQL script example for this...

    thanks for any reply......

  • Leave off the triggers. consider cascading deletes on your foreign key relationships.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • How can I do the cascade delete...???

    any example... pls....thnx

  • Look up ALTER TABLE in Books online and check the section on foreign key constraints.

    You set the cascading properties when you create the foreign key. If the constraint is set to prevent deletes (the default), you'll have to drop it and recreate with the cascade option.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • just to add to Gails reply..

    be sure to provide indexes that match your FK-declaration !

    (because otherwise you 'll end up with dependant table scans !!)

    Johan

    Learn to play, play to learn !

    Dont drive faster than your guardian angel can fly ...
    but keeping both feet on the ground wont get you anywhere :w00t:

    - How to post Performance Problems
    - How to post data/code to get the best help[/url]

    - How to prevent a sore throat after hours of presenting ppt

    press F1 for solution, press shift+F1 for urgent solution 😀

    Need a bit of Powershell? How about this

    Who am I ? Sometimes this is me but most of the time this is me

Viewing 5 posts - 1 through 4 (of 4 total)

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