Why does SQL Server keep creating a DF constraint?

前端 未结 3 1746
离开以前
离开以前 2021-01-31 14:31

I\'m trying to create upgrade and backout scripts in SQL. The upgrade script adds a column like so:

IF NOT EXISTS (SELECT * FROM sys.columns WHERE Name = N\'Col         


        
相关标签:
3条回答
  • 2021-01-31 14:47

    Run this:

    declare @name as nvarchar(255);
    SELECT @name = name FROM dbo.sysobjects 
    WHERE name LIKE 'DF__XXX__YYY__%' and type = 'D'
    
    IF @name IS NOT NULL BEGIN
        EXEC('ALTER TABLE XXX DROP CONSTRAINT ' + @name);
    END
    
    0 讨论(0)
  • 2021-01-31 14:57

    This is the default constraint that is added because of the DEFAULT(0) in your newly added column.

    You can name this yourself so it has a known fixed name rather than relying on the auto name generation.

    ALTER TABLE TableName
        ADD ColumnName bit NOT NULL CONSTRAINT DF_Some_Fixed_Name DEFAULT(0) 
    

    Then to remove the column and constraint together

    ALTER TABLE dbo.TableName
    DROP CONSTRAINT DF_Some_Fixed_Name, COLUMN ColumnName
    
    0 讨论(0)
  • 2021-01-31 15:09

    Run this if you want remove constraint:

    DECLARE @tableName NVARCHAR(255) = '[INSERT]';
    DECLARE @first5CharsFromColumnName NVARCHAR(255) = '[INSERT]';
    DECLARE @name NVARCHAR(255);
    SELECT @name = d.name FROM dbo.sysobjects d
    INNER JOIN dbo.sysobjects t ON t.id = d.parent_obj
    WHERE d.name LIKE '%'+@first5CharsFromColumnName+'%' AND d.type = 'D' AND t.name = @tableName
    
    IF @name IS NOT NULL BEGIN
        EXEC('ALTER TABLE '+@tableName+' DROP CONSTRAINT ' + @name);
    END
    
    0 讨论(0)
提交回复
热议问题