删除查询以从sql server和c#中的多个表中删除数据

时间:2014-07-21 16:19:10

标签: c# asp.net sql sql-server

我有三个表mainCategorysubCategoryproducts。我在gridview中显示数据。我想从管理面板中删除主要类别,但到时候我还需要从子类别表中删除数据,并根据主类别表删除包含数据的产品。

这些是表格中的列:

  1. mainCategory

    mainCatID (primary key)  
    mainCatName
    
  2. subCategory

    subCatId (primary key) 
    mainCatId
    subCatName 
    mainCatName
    
  3. products

    productId (primary key) 
    subCatId 
    subCatName  
    productName 
    productImage
    
  4. SqlCommand对象中写入什么SQL? Gridview使用函数绑定表单代码。请帮助我

2 个答案:

答案 0 :(得分:2)

喜欢这个?最简单的做法就是三个单独的陈述。

DELETE FROM Products WHERE SubCatId IN (SELECT SubCatID FROM SubCategory WHERE MainCatId = @mainCatId);
DELETE FROM SubCategory WHERE MainCatId = @mainCatId;
DELETE FROM MainCategory WHERE MainCatId = @mainCatId;

答案 1 :(得分:1)

这里有两种可能性。一,您在这三个表之间的关系上启用了级联删除。如果是这种情况,那么它就像下面那样简单(假设没有周期/多个级联路径):

DELETE
FROM mainCategory WHERE mainCatID = @someId

如果您没有启用级联删除功能,那么这将分为三个步骤:

-- remove the products
DELETE a 
FROM products as a
JOIN subcategory as b 
ON a.subCatId = b.subCatId 
AND b.mainCatID = @someId

-- remove the subcategories
DELETE
FROM subcategory WHERE mainCatID = @someId

-- remove main categories
DELETE
FROM products WHERE mainCatID = @someId