2

I have a simple script, which display all constraints of some table:

SELECT *
FROM DB_NAME.INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'TestTable'

How I can drop all constraints in TestTable and use selection of previous query (MS SQL Server 2012)? Or it will be bad way to drop constraints?

I found some solutions, but I don't understand where they get information about constraints.

user183101
  • 151
  • 1
  • 3
  • 13

1 Answers1

3

Try to build a string with script like:

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

SELECT @sql += N'
ALTER TABLE ' + TABLE_NAME +
    ' DROP CONSTRAINT ' + CONSTRAINT_NAME + ';'
DB_NAME.INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE
WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'TestTable';

EXEC sp_executesql @sql;
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116