在许多列上删除SQL Server中的默认约束

时间:2014-02-11 19:17:51

标签: sql sql-server-2008 tsql

对于SQL Server 2008 R2,我想删除允许为null且约束包含1899的日期列的默认约束。我想要一个可以测试然后在实时执行的脚本。我不想在现场环境中摆弄这个。脚本的另一个原因是有几个具有相同方案的数据库

在Google的帮助下,我有以下列出列

的脚本
SELECT tables.name, all_columns.name, all_columns.is_nullable, default_constraints.name, default_constraints.definition
FROM 
    sys.all_columns
        INNER JOIN
    sys.tables
        ON all_columns.object_id = tables.object_id
        INNER JOIN 
    sys.schemas
        ON tables.schema_id = schemas.schema_id
        INNER JOIN
    sys.default_constraints
        ON all_columns.default_object_id = default_constraints.object_id
WHERE 
        schemas.name = 'dbo'
    and default_constraints.definition like '%1899%'
    and all_columns.is_nullable = 1
order by tables.name, all_columns.name, default_constraints.name

现在这个列表超过了100列。下一个脚本执行我想要的CargoPool.Created列。但是,如何迭代从第一个脚本创建的所有行?

DECLARE @tableName VARCHAR(MAX) = 'CargoPool'
DECLARE @columnName VARCHAR(MAX) = 'Created'
DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name 
FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID(@tableName) 
AND PARENT_COLUMN_ID = (
    SELECT column_id FROM sys.columns
    WHERE NAME = @columnName AND object_id = OBJECT_ID(@tableName))
IF @ConstraintName IS NOT NULL
    EXEC('ALTER TABLE '+@tableName+' DROP CONSTRAINT ' + @ConstraintName)

1 个答案:

答案 0 :(得分:3)

如果要从第一个查询中删除所有约束,可以使用该查询的结果构建动态SQL,然后执行它:

DECLARE @sql AS NVARCHAR(MAX) = N''

SELECT @sql = @sql + N'ALTER TABLE ' 
      + QUOTENAME(schemas.name) + N'.' + QUOTENAME(tables.name) 
      + N' DROP CONSTRAINT ' + QUOTENAME(default_constraints.name) + N'; '
FROM 
    sys.all_columns
        INNER JOIN
    sys.tables
        ON all_columns.object_id = tables.object_id
        INNER JOIN 
    sys.schemas
        ON tables.schema_id = schemas.schema_id
        INNER JOIN
    sys.default_constraints
        ON all_columns.default_object_id = default_constraints.object_id
WHERE 
        schemas.name = N'dbo'
    and default_constraints.definition like N'%1899%'
    and all_columns.is_nullable = 1
order by tables.name, all_columns.name, default_constraints.name

exec sp_executesql @sql;