CREATE TABLE [dbo].[tmp_rg_xx_LBJ]
(
[ROWVERSION] [bigint] NULL,
[ROWDATE] [datetime] NULL,
[SAPNO] [int] NOT NULL DEFAULT 1)
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[DF__tmp_rg_xx__SAPNO__1B0907CE]') AND type = 'D')
BEGIN
ALTER TABLE [dbo].[LBJ] DROP CONSTRAINT [DF__tmp_rg_xx__SAPNO__1B0907CE]
END
GO
我有一个脚本可以创建一个默认的表格,但我想放弃约束。我知道名字手动没问题,除了我想在重新创建表后删除约束。所以我可以重新运行drop constraint脚本。如果没有明确使用名称,你怎么做?
答案 0 :(得分:1)
您可以尝试这一点 - 这将在系统目录视图中查找必要的信息,并创建一个“drop”T-SQL命令,您可以复制&执行以摆脱系统命名的默认约束:
SELECT
DropCmd = 'ALTER TABLE ' + t.name + ' DROP CONSTRAINT ' + df.Name
FROM sys.default_constraints df
INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id
INNER JOIN sys.tables t ON c.object_id = t.object_id
WHERE
t.Name = 'YourTableNameHere'
AND c.name = 'YourColumnNameHere'
如果需要将它放入自己的脚本中 - 可以将DropCmd
分配给变量,然后使用动态SQL执行该SQL语句:
DECLARE @DropStatement NVARCHAR(200)
SELECT
@DropStatement = N'ALTER TABLE ' + t.name + N' DROP CONSTRAINT ' + df.Name
FROM sys.default_constraints df
INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id
INNER JOIN sys.tables t ON c.object_id = t.object_id
WHERE
t.Name = 'YourTableName'
AND c.name = 'YourColumnName'
EXEC sp_executesql @DropStatement