Drop all constraints in SQL database

Last modified 2 years ago
Danger icon
The last modifications of this post were around 2 years ago, some information may be outdated!

Summary

If you need to remove all the constraints before manipulating some data. This script will do that.

Code

DECLARE @dropAllConstraints NVARCHAR(MAX) = N'';

SELECT @dropAllConstraints += N'
ALTER TABLE '
+ QUOTENAME(OBJECT_SCHEMA_NAME(parent_object_id))
+ '.' + QUOTENAME(OBJECT_NAME(parent_object_id)) +
' DROP CONSTRAINT ' + QUOTENAME(name) + ';'
FROM sys.foreign_keys;
EXEC sp_executesql @dropAllConstraints