Asp.net 是否同时从两个表中删除?

Asp.net 是否同时从两个表中删除?,asp.net,sql-server,stored-procedures,Asp.net,Sql Server,Stored Procedures,我正在使用asp.net和sql server。我有两个表:类别和产品。在products表中,我的类别ID为FK。我想做的是:当我从category表中删除category时,我希望该类别中的所有产品都将在products表中删除。如何做到这一点(我更喜欢存储过程,但它不是强制性的) @categoryid正在进入存储过程 delete from products where categoryid = @categoryid delete from categories where cate

我正在使用asp.net和sql server。我有两个表:类别和产品。在products表中,我的类别ID为FK。我想做的是:当我从category表中删除category时,我希望该类别中的所有产品都将在products表中删除。如何做到这一点(我更喜欢存储过程,但它不是强制性的)

@categoryid正在进入存储过程

delete from products where  categoryid = @categoryid
delete from categories where categoryid = @categoryid

您可以定义要使用的FK。否则,您需要先删除该类别中的所有产品,然后再删除该类别。

有很多方法可以做到这一点。我会在SQL中的外键约束中将删除设置为“级联”。让SQL为您管理它,这是它擅长的。

如果您可以调整模式,SQL Server支持。使用这种FK约束,只需对类别进行一次删除即可获得此效果。注意,不是每个人都喜欢级联删除

您可以通过在数据库的“图表”部分(假设为MS SQL 2005/2008)或屏幕顶部的“关系”按钮(SQL 2000)中创建表之间的关系来实现这一点

使用cascade delete创建一对多关系后,查询可以很简单:

delete from Categories where CategoryId = XX

这将自动删除与该类别关联的所有产品。

如果要使用存储过程执行此操作

delete from Categories where categoryId=@categoryId 
delete from Products where categoryId = @categoryId
如果这种情况总是发生的话,也就是说,如果你从分类表中删除了一些东西,它应该从产品中删除。我的选择是删除级联。类似这样的

ALTER TABLE dbo.Products   
WITH CHECK ADD  CONSTRAINT FK_Products_Categories FOREIGN KEY([categoryId])
REFERENCES dbo.Categories([categoryId])
ON DELETE CASCADE
所以,当您从类别表中删除时,它也会自动从产品表中删除

e、 g:
从dbo中删除categoryId=@categoryId

   no use of writing 

   delete from Products where categoryId = @categoryId

如果你得到了答案。请选择一个正确答案。在已提供的答案旁边有一个灰色的勾号。然后选择与您认为最适合回答问题的答案相对应的答案。