I need to remove a highly referenced table in a SQL Server database. How can I get a list of all the foreign key constraints I will need to remove in order to drop the table?
(SQL answers preferable over clicking about in the GUI of the management studio.)
Here's the SQL code I would use.
It's not particularly clear SQL, so let's look at an example.
So, supposing I wanted to drop the
Employees
table in Microsoft's belovedNorthwind
database, but SQL Server told me that one or more Foreign Keys were preventing me from doing this.The SQL command above would return these results...
It shows me that there are 3 Foreign Keys which reference the
Employees
table. In other words, I wouldn't be allowed to delete (drop) this table until these three Foreign Keys are first deleted.In the results, the first row is how the following Foreign Key constraint would be shown in the results.
The second-to-last column shows the SQL command I would need to use to delete one of these Foreign Keys, eg:
...and the right-hand column shows the SQL to create it...
With all of these commands, you have everything you need to delete the relevant Foreign Keys to allow you to delete a table, then recreate them later.
Phew. Hope this helps.
Some good answers above. But I prefer to have the answer with one query. This piece of code is taken from sys.sp_helpconstraint (sys proc)
That's the way Microsoft looks up if there are foreign keys associated to the tbl.
The answer will look like this: test_db_name.dbo.Account: FK_Account_Customer
Determine primary keys and unique keys for all tables in a database...
This should list all the constraints and at the end you can put your filters
For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx