Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql server - recursive delete

I'm trying to delete user's data and all it's related data that is located in different tables. All the tables have Foreign Keys but without cascade delete.

I investigated some options:

  1. Enable cascade delete on all FK, delete and remove the cascade delete.
  2. Delete from bottom UP, loop up for all the leaves delete and repeat this operation till Root.

Are there any more smart option or other Techniques?

I'm using Microsoft SQL Server 2012 (SP1)

like image 897
ron Avatar asked Jul 25 '13 10:07

ron


People also ask

What is cascading delete in SQL Server?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.

Can you do recursion in SQL?

Recursion is achieved by WITH statement, in SQL jargon called Common Table Expression (CTE). It allows to name the result and reference it within other queries sometime later.

How recursive CTE works in SQL Server?

A recursive CTE references itself. It returns the result subset, then it repeatedly (recursively) references itself, and stops when it returns all the results. FROM cte_name; Again, at the beginning of your CTE is the WITH clause.

What is recursive query in SQL Server?

A recursive query is one that is defined by a Union All with an initialization fullselect that seeds the recursion. The iterative fullselect contains a direct reference to itself in the FROM clause. There are additional restrictions as to what can be specified in the definition of a recursive query.


1 Answers

Those are the best and most efficient ones. For production queries I would use 2.

The only other ways I can think of would (IMO) only be suitable for quick and dirty removal of data in a test environment (avoiding the need to analyse the correct order)

  1. Disable all FKs delete the desired data then re-enable the FKs. This is inefficient as they need to be re-enabled WITH CHECK to avoid leaving the FKs in an untrusted state which means that all preserved data needs to be re-validated.
  2. List out all DELETE statements on affected tables in arbitrary order and run the batch as many times as necessary until it succeeds with no FK errors.
like image 182
Martin Smith Avatar answered Sep 30 '22 19:09

Martin Smith