简体   繁体   中英

Delete Parent and child tables without using cascade delete (SQL Server 2012 or .net 4)

Working with a SQL Server 2012 database and I need to implement a functionality to allow to delete a row in a table and all it's referenced children based on a foreign key constraint.

Given that Cascade delete is out of the question since I cannot touch this database, has anybody written a stored procedure or some code in C# that deletes a parent row and all it's children however deep the children go using their foreign keys?

Or a link /article with some pointers?

Example

Tables:

  1. Customer
  2. CustomerAddress
  3. CustomerAddress
  4. CustomerProducts
  5. ProductOrdered

If I decide to delete a customer with an Id=1 , it should delete

  • a row from the CustomerTable
  • all the rows from CustomerAddress with a customerId=1
  • all customerProducts that belong to CustomerId=1
  • All ProductOrdered that belong to that Customer with an associated customerProductId

Basically we only have the knowledge of the root table Customer and it's CustomerId (generic implementation).

Open to any suggestions that does not involve 3rd party tools.

Many thanks for any suggestion

The basic logic is to remove from the bottom of the hierarchy (the deepest nested) first, and remove references along the way.

If you're using an ORM something like this.

foreach(var c in Customer)
{
    var caToClear = c.CustomerAddress().ToList();
    c.CustomerAddress.RemoveAll();
    foreach(var ca in c.caToClear)
    {
        ca.Delete();
    }

    var cpToClear = c.CustomerProducts.ToList();
    c.CustomerProducts.RemoveAll();
    foreach(var cp in cpToClear)
    {
        var poToClear = cp.ProductOrdered.ToList();
        cp.ProductOrdered.RemoveAll();
        foreach(var po in poToClear)
        {
            po.Delete();
        }
        cp.Delete();
    }
    c.Delete();
}

To do the same in SQL

DELETE FROM productordered 
WHERE  id IN (SELECT product_ordered_id 
              FROM   customerproducts 
              WHERE  customer_id = id_to_delete) 

DELETE FROM customeraddress 
WHERE  id IN (SELECT customer_address_id 
              FROM   customer 
              WHERE  customer_id = id_to_delete) 

DELETE FROM customer 
WHERE  id = id_to_delete 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM