Search code examples
sqlsql-server-2008sql-order-bysql-deleteself-reference

SQL Server 2008 Delete Records from Self-Referencing Table in correct order


Possible Duplicate:
SQL: DELETE data from self-referencing table in specific order

I need to delete a sub set of records from a self-referencing table in SQL Server 2008. I am trying to do the following but it is does not like the order by.

WITH SelfReferencingTable (ID, depth)
AS
(
   SELECT id, 0 as [depth]
   FROM dbo.Table
   WHERE parentItemID IS NULL AND [t].ColumnA = '123'
   UNION ALL
   SELECT [t].ID, [srt].[depth] + 1 
   FROM dbo.Table t 
   INNER JOIN SelfReferencingTable srt ON [t].parentItemID = [srt].id
   WHERE [t].ColumnA = '123'       
)   
DELETE y FROM dbo.Table y
JOIN SelfReferencingTable x on x.ID = y.id
ORDER BY x.depth DESC

Any ideas why this isn't working?


Solution

  • You don't need to delete them in any particular order.

    Just delete them all in one operation. The constraints are checked at the end of the statement.

    Assuming that your recursive CTE code correctly identifies all the rows that you need to delete you can just use

    WITH SelfReferencingTable (ID)
    AS
    (
       SELECT id
       FROM dbo.Table
       WHERE parentItemID IS NULL AND [t].ColumnA = '123'
       UNION ALL
       SELECT [t].ID 
       FROM dbo.Table t 
       INNER JOIN SelfReferencingTable srt ON [t].parentItemID = [srt].id
       WHERE [t].ColumnA = '123'       
    )   
    DELETE 
    FROM dbo.Table 
    WHERE ID IN (SELECT id FROM SelfReferencingTable )