Roland Bengtsson
Roland Bengtsson

Reputation: 5166

Drop default constraint in SQL Server on many columns

For SQL Server 2008 R2 I want to remove default constraints for date columns that allow null and the constraint contains 1899. And I want a script that can tested and then executed in live. I don't wan't to fiddle with this in live environment. Another reason for a script is that there is several databases with the same scheme

With help from Google I have the following script that list columns

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

Now this list over hundred columns. The next script do what I want for the column CargoPool.Created. But how can I iterate all rows created from my first script ?

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)

Upvotes: 1

Views: 303

Answers (1)

Szymon
Szymon

Reputation: 43023

If you want to drop all the constraints from your first query, you can build up a dynamic SQL with the results of that query and then execute it:

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;

Upvotes: 3

Related Questions