Where to use foreign key and triggers

  • Hi

    could some one tell me in what situation we can use foreign key and triggers.

  • Firstly, I will suggest that you read Books Online (SQL help file) as there's a lot of very good info in there.

    Foreign keys are used to enforce referential integrity between tables.

    Say there's a table product which has columns ProductCode, Description, Price. Then there's an orders table Which has the ProductCode, quantity, date. A foreign key on the ProductCode column in the orders table references the ProductCode column of the products table, and prevents anyone inserting a product code that doesn't exist in the products table.

    Triggers are a little more comples. They fire when a data modification is made to a table. Inside a trigger you've got access to the rows that were inserted/updated/deleted. Often they're used for auditing, though there are a lot of other uses.

    does that help?

    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
  • thank you!

  • I used books by WROX to learn SQL Server years ago. I found they were very easy to read and very helpful. The one I mostly used was for SQL Server 7.0 and it explained Foreign Keys and Triggers very well - when to use them and when not to. I'm sure the most recent books for 2005 will do the same.

    A word of caution. Use triggers sparingly and only when they make a lot of sense. Databases where triggers do the majority of the business logic can be a nightmare and tend to be very sluggish.

    Todd Fifield

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

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