Drop all constraints in SQL database

Last modified 1 year ago
Danger icon
The last modifications of this post were around 1 year 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