Ali Khan
Ali Khan

Reputation: 91

Deleting multiple tables from SQL Server 2008 using Datalist C#

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?

Upvotes: 2

Views: 760

Answers (1)

user596075
user596075

Reputation:

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.

Upvotes: 4

Related Questions