2

This may seem a common question but I googled to find the right answer that can fix my problem and failed to do so.

I have multiple tables connected to each other by ProductID and I wish to delete all data from them when the product from main table has been deleted. i.e.

Products : ProductID - Vender - Description

ProductRatings : ProductID - Rating - VisitorsCount

ProductComments : ProductID - VisitorName - Comment

I read that for such situation a SQL trigger is used but I have no idea about it besides I might be mentioning my DataSource in ASCX.CS file in some cases and in some cases I might simply use SqlDatasoruce in ASCX file. Is there any query or stored procedure that can be used?

1 Answer 1

4

The easiest way to do this is to implement a foreign key relationship to ProductID and set on delete cascade. This is a general idea:

create table ProductRatings
(
    ProductID int not null 
        foreign key references Products(ProductID) on delete cascade,
    Rating int not null,
    VisitorsCount int not null
)

What that does is when you delete a primary key value from the Products table, that causes SQL Server to delete all records that have a foreign key constraint to that primary key value. If you do this with your ProductComments table as well, problem solved. No need to explicitly call a DELETE on any records in the referencing tables.

And if you aren't using referential integrity...you should.

EDIT: this also holds true for UPDATEs on the primary key. You just need to specify on update cascade, and the foreign key references will update as the primary key did to ensure RI.

4
  • 1
    For data consistency, this is much better than trying to implement a bunch of triggers. It also encourages the dev to set up proper foreign key relationships in the database.
    – NotMe
    Mar 7, 2012 at 17:25
  • Agree with @ChrisLively. In fact, I would go so far as to say triggers should always be a last resort. They often cause more problems than they solve.
    – JamieSee
    Mar 7, 2012 at 17:42
  • Thank you so much Shark, you not only solved this problem but also gave me great knowledge that will be very useful in future also.... I hope same can work with Insert and Update as well.
    – Ali Khan
    Mar 7, 2012 at 17:49
  • @AliKhan See my edit. It also worked for UPDATEs, but INSERTs will explicitly need an INSERT into the referencing table, if that makes sense.
    – user596075
    Mar 7, 2012 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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