DECLARE @sql NVARCHAR(MAX);
SET @sql = N'';
SELECT @sql = @sql + N'
ALTER TABLE ' + QUOTENAME(s.name) + N'.'
+ QUOTENAME(t.name) + N' DROP CONSTRAINT '
+ QUOTENAME(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')
ORDER BY c.[type];
PRINT @sql;
--EXEC sys.sp_executesql @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
sys.tables.object_id = sys.objects.parent_object_id
您可以通过加入这些对象类型轻松获取此信息。PRINT
只是用于目测,而不是用于复制和粘贴输出(如果您想运行它,这就是注释掉的EXEC
用途)-如果您有很多限制,它可能不会显示整个脚本,因为PRINT
仅限于4,000 个字符 (8kb)。在这些情况下,如果您需要验证整个脚本,请参阅此提示以了解在运行之前验证脚本的其他方法。例如:对输出感到满意后,取消注释
EXEC
.我从接受的答案开始,并修改了结构以使用 while 循环,而不是在动态 sql 中构建完整的 sql 语句。我更喜欢这个有几个原因。
查询未存储在大 @sql 变量中。此实现允许在输出中删除用于记录目的的每个约束的打印。在我的单元测试中,执行似乎快了一点。