Currently I am working in a DB with a tree-like structure. Basically there is one top level table, and there are about 10 tables that have a foreign key on that table. Each of these tables has another 10 tables with a foreign key constraint. Now my goal is to delete some records from the main table, and also delete the children, grandchildren etc. but of course the foreign keys make this a painstaking task.
I have searched a bit and came across checked this question on using cascade delete and I guess this would do the trick if I was dealing with only a few tables. However, in my current setting it would still not be pleasant to alter over 100 tables one by one.
Therefore I am asking whether there is an easy way to delete values that have foreign keys when many tables are involved.
As I have some control over the relatively small DB, query efficiency and the risk of values being deleted by others are not really a concern. So it may be easy to apply cascade delete on all tables, but I am also open to completely different solutions (Using T-SQL in microsoft server studio 2008).
The delete cascade would be a good solution for a “main” table.
To avoid altering manually all your tables, you can use a script, as found here with a minor change (last line, change
<yourTable>by your table Name).You copy the first column result in a Management Studio query window, execute, then do the same with the second column, and voilà, you’re done.