I want to drop all default constraints, check constraints, unique constraints, primary keys and foreign keys from all tables in a SQL Server database. I know how to get all the constraint names from sys.objects
, but how do I populate the ALTER TABLE
part?
SQL Server – How to Drop All Constraints from All Tables
constraintddlsql server
Related Question
- PostgreSQL – Recreate All Foreign Keys as Deferrable in Batch
- Oracle – SQL Error OA-12991 When Dropping Column After Removing Multi-Column Constraints
- PostgreSQL – How to Duplicate Constraints Between Tables with Identical Structure
- Oracle Foreign Keys – How to Truncate Table with Foreign Keys
- SQL Server – Difference Between Key and Constraint
Best Answer
You can derive this information easily by joining
sys.tables.object_id = sys.objects.parent_object_id
for those object types.PRINT
is just there for eyeballing, not for copying and pasting the output (if you want to run it, that's what the commented-outEXEC
is for) - if you have a lot of constraints, it may not show the entire script becausePRINT
is limited to 4,000 characters (8kb). In those cases, if you need to validate the entire script, see this tip for other ways to validate the script before running. For example:Once you are happy with the output, uncomment the
EXEC
.