Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to drop
and then re-create
the constraints?
Sql-server – How to foreign key constraints be temporarily disabled using T-SQL
constraintsforeign-keyssql-servertsql
Related Question
- Sql-server – Check if table exists in SQL Server
- Mysql – How to see all foreign keys to a table or column
- Sql-server – Cannot truncate table because it is being referenced by a FOREIGN KEY constraint
- Sql – How to list all foreign keys referencing a given table in SQL Server
- Sql-server – Altering a column: null to not null
- Sql – How to UPDATE from a SELECT in SQL Server
- Sql – Can a foreign key be NULL and/or duplicate
- MySQL Cannot Add Foreign Key Constraint
Best Solution
If you want to disable all constraints in the database just run this code:
To switch them back on, run: (the print is optional of course and it is just listing the tables)
I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment).
If you are deleting all the data you may find this solution to be helpful.
Also sometimes it is handy to disable all triggers as well, you can see the complete solution here.