views:

51

answers:

3

This is for a MS SQL 2005 server. I have a query that is deleting all orphaned records in a table. However, this table has self-referencing FKs. I need to delete these as well, but am unclear how to do so. The current script deletes all records that not appear as FKs in other tables, but i didn't take into account the self-referencing FKs in its own table. the table is simple:

PK, FK, DAta
1, NULL, jibberjab
2, 1, jibberjab2
3, 1, skdfasfa
A: 

It's probably simplest to do this in two steps, first delete the orphaned records, then to delete the referenced children now orphaned after the first delete:

DELETE FROM TABLE1
WHERE NOT EXISTS (SELECT 1 FROM TABLE2 WHERE TABLE2.FK = TABLE1.PK)

DELETE FROM TABLE1 
WHERE NOT EXISTS (SELECT 1 FROM TABLE1 B WHERE B.FK = TABLE1.PK)
Russ
A: 

Probably you can configure your constraint to be deleted on parent item deletion:

ALTER TABLE table1 WITH CHECK ADD CONSTRAINT FK_table1_table2 FOREIGN KEY(column1)
REFERENCES table2 (ID) ON DELETE SET NULL -- here
ALTER TABLE table1 CHECK CONSTRAINT FK_table1_table2
GO
abatishchev
+1  A: 

If you are going to have multiple levels, you can use a common table expression to get the IDs you need to delete and take care of the orphans and all their descendants in one statement:

    WITH cte AS (
        SELECT pk
        FROM myTable
        WHERE id = 1  --pk to delete
        UNION ALL
        SELECT t.pk
        FROM myTable t
        JOIN cte c
            ON t.fk = c.pk
    )
    DELETE t
    FROM cte c
    JOIN myTable t
        ON c.id = t.id
Zugwalt