我从公认的答案开始,并修改了结构以使用while循环,而不是在动态sql中构建完整的sql语句。我更喜欢这样做有几个原因。
该查询未存储在大@sql变量中。此实现允许为输出中记录的每个约束删除“打印”。在我的单元测试中,执行似乎要快一些。
Set NoCount ON
Declare @schemaName varchar(200)
set @schemaName=''
Declare @constraintName varchar(200)
set @constraintName=''
Declare @tableName varchar(200)
set @tableName=''
While exists
(
SELECT c.name
FROM sys.objects AS c
INNER JOIN sys.tables AS t
ON c.parent_object_id = t.[object_id]
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE c.[type] IN ('D','C','F','PK','UQ')
and t.[name] NOT IN ('__RefactorLog', 'sysdiagrams')
and c.name > @constraintName
)
Begin
-- First get the Constraint
SELECT
@constraintName=min(c.name)
FROM sys.objects AS c
INNER JOIN sys.tables AS t
ON c.parent_object_id = t.[object_id]
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE c.[type] IN ('D','C','F','PK','UQ')
and t.[name] NOT IN ('__RefactorLog', 'sysdiagrams')
and c.name > @constraintName
-- Then select the Table and Schema associated to the current constraint
SELECT
@tableName = t.name,
@schemaName = s.name
FROM sys.objects AS c
INNER JOIN sys.tables AS t
ON c.parent_object_id = t.[object_id]
INNER JOIN sys.schemas AS s
ON t.[schema_id] = s.[schema_id]
WHERE c.name = @constraintName
-- Then Print to the output and drop the constraint
Print 'Dropping constraint ' + @constraintName + '...'
Exec('ALTER TABLE [' + @schemaName + N'].[' + @tableName + N'] DROP CONSTRAINT [' + @constraintName + ']')
End
Set NoCount OFF