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?
The easiest way to do this is to implement a foreign key relationship to
ProductIDand seton delete cascade. This is a general idea:What that does is when you delete a primary key value from the
Productstable, that causes SQL Server to delete all records that have a foreign key constraint to that primary key value. If you do this with yourProductCommentstable as well, problem solved. No need to explicitly call aDELETEon 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 specifyon update cascade, and the foreign key references will update as the primary key did to ensure RI.