I need to delete many rows from one table persons, that is referenced by many other tables as FK.
If I had DELETE CASCADE, I could just delete the records from persons, and automatically delete from the other tables, but I don't like the idea.
I would like a script that takes as input a DELETE statement, and outputs all the DELETE statements that are needed. Ideally, it would tell me how many records would be deleted.
Example:
Input:
DELETE FROM persons WHERE person_id < 1000000
Output:
-- This would delete 124,345 records
DELETE FROM persons_addresses WHERE person_id < 1000000
-- This would delete 82,954 records
DELETE FROM persons_phone numbers WHERE person_id < 1000000
...
-- This would delete 999,999 records
DELETE FROM persons WHERE person_id < 1000000
Best Answer
The information required to generate the queries and the counts is all available in the catalog views, like
sys.columns
andsys.foreign_key_columns
. We need to find all of the child tables, and then count how many rows in each child table meet the same criteria as the parent ID.Sample usage:
My sample tables were much smaller, but my output looked like this:
Limitations: