views:

429

answers:

3

I have a list of half a dozen MSSQL 2008 tables that I would like to remove at once from my database. The data has been entirely migrated to new tables. There is no reference in the new tables to the old tables.

The problem being that old tables comes with loads of inner FK constraints that have been autogenerated by a tool (aspnet_regsql actually). Hence dropping manually all constraints is a real pain.

How can I can drop the old tables ignoring all inner constraints?

+1  A: 

A simple DROP TABLE dbo.MyTable will ignore all constraints (and triggers) except foreign keys (unless you drop the child/referencing table first) where you may have to drop these first.

Edit: after comment:

There is no automatic way. You'll have to iterate through sys.foreign_keys and generate some ALTER TABLE statements.

gbn
Thanks, but my problem is that precisely there are loads of generated FK.
Joannes Vermorel
A: 

I suspect that you would have to do an 'alter' command on the offending tables before the drop to remove the forigen key contraints.

ALTER TABLE Orders DROP FOREIGN KEY fk_PerOrders;
DROP TABLE Orders;

Of course if you drop the child tables first, then you wont have this problem. (unless you have table A contraint to table B and table B constraint to A, then you will need to Alter one of the tables, e.g. A to remove the constraint)

e.g. this WONT work, since Orders has a contraint from Order_Lines

DROP TABLE Orders;
DROP TABLE Order_lines;

e.g. this will work

DROP TABLE Order_lines;
DROP TABLE Orders;
jeff porter
Sorry, but there are tons of auto-generated constraints, can't manually list constraints.
Joannes Vermorel
How are the tables created? I feel that you will just need to manually create a script that deletes the tables with no constraints and then alters the other tables before deleting them. I know its not the answer you are looking for, but its the best approach I can offer.I have in my project something simuliar, a 40 line sql statement that alters rows and then drops them (not tables in my case).
jeff porter
A: 

I finally found the solution based on the script provided by Jason Presley. This script automatically removes all constraints in the DB. It's easy to add a WHERE clause so that it only applies to the set of concerned tables. After that, dropping all tables is a straightforward.

Joannes Vermorel