1
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

我有一个脚本可以创建一个带有默认值的表,但我想删除约束。手动没有问题,因为我知道名称,除了我想在重新创建表后删除约束。所以我可以重新运行放置约束脚本。在不明确使用名称的情况下如何做到这一点?

4

1 回答 1

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
于 2012-10-18T13:19:53.270 回答