我想删除SQL Server数据库中的每个用户对象,但保留表及其记录不变。但我也想放弃它的限制。所以我创建了这个查询以获取我将粘贴到SMSS并在执行之后执行的drop声明:
SELECT
'DROP ' +
CASE
WHEN [sys].[all_objects].type IN ('AF','FN','FS','FT','IF','TF') THEN 'FUNCTION '
WHEN [sys].[all_objects].type IN ('D','C','F','PK','UQ') THEN 'CONSTRAINT '
WHEN [sys].[all_objects].type IN ('IT','S','U') THEN 'TABLE '
WHEN [sys].[all_objects].type IN ('P','PC','RF','X') THEN 'PROCEDURE '
WHEN [sys].[all_objects].type IN ('TA','TR') THEN 'TRIGGER '
WHEN [sys].[all_objects].type = 'R' THEN 'RULE '
WHEN [sys].[all_objects].type = 'SN' THEN 'SYNONYM '
WHEN [sys].[all_objects].type = 'TT' THEN 'TYPE '
WHEN [sys].[all_objects].type = 'V' THEN 'VIEW '
END +
SCHEMA_NAME(sys.[all_objects].[schema_id]) + '.' + OBJECT_NAME(object_id) + '; ', OBJECT_NAME(object_id), [sys].[all_objects].[type_desc], [sys].[all_objects].[type], SCHEMA_NAME(sys.[all_objects].[schema_id])
FROM
sys.[all_objects] WITH (NOLOCK) -- WHERE (OBJECT_DEFINITION(object_id) LIKE '%' + @toDrop + '%') AND ([sys].[all_objects].[name] <> @toDrop);
WHERE
(SCHEMA_NAME(sys.[all_objects].[schema_id]) <> 'sys') AND
(SCHEMA_NAME(sys.[all_objects].[schema_id]) <> 'INFORMATION_SCHEMA') AND
([sys].[all_objects].[type_desc] <> 'USER_TABLE')
ORDER BY
[sys].[all_objects].[type_desc], SCHEMA_NAME(sys.[all_objects].[schema_id]), OBJECT_NAME(object_id)
问题是,在约束情况下,我必须使用ALTER TABLE x DROP CONSTRAINT y
那么如何轻松删除所有约束?
答案 0 :(得分:0)
SELECT
'ALTER TABLE ' +
SCHEMA_NAME(sys.[objects].[schema_id]) + '.' + OBJECT_NAME([sys].[objects].[parent_object_id]) +
' DROP CONSTRAINT ' +
OBJECT_NAME(object_id) + '; ', OBJECT_NAME(object_id), [sys].[objects].[type_desc], [sys].[objects].[type], SCHEMA_NAME(sys.[objects].[schema_id]),
OBJECT_NAME([sys].[objects].[parent_object_id])
FROM
sys.[objects] WITH (NOLOCK)
WHERE
(SCHEMA_NAME(sys.[objects].[schema_id]) <> 'sys') AND
([sys].[objects].[type_desc] <> 'USER_TABLE') AND
([sys].[objects].TYPE IN ('D','C','F','PK','UQ')) AND
ORDER BY
[sys].[objects].[type_desc], SCHEMA_NAME(sys.[objects].[schema_id]), OBJECT_NAME(object_id)
GO