How to drop column with constraint?

后端 未结 8 577
半阙折子戏
半阙折子戏 2020-11-29 16:58

How to drop a column which is having Default constraint in SQL Server 2008?

My query is

alter table tbloffers
drop column checkin

8条回答
  •  Happy的楠姐
    2020-11-29 17:30

    You can also drop the column and its constraint(s) in a single statement rather than individually.

    CREATE TABLE #T
      (
         Col1 INT CONSTRAINT UQ UNIQUE CONSTRAINT CK CHECK (Col1 > 5),
         Col2 INT
      )
    
    ALTER TABLE #T DROP CONSTRAINT UQ , 
                        CONSTRAINT CK, 
                        COLUMN Col1
    
    
    DROP TABLE #T 
    

    Some dynamic SQL that will look up the names of dependent check constraints and default constraints and drop them along with the column is below

    (but not other possible column dependencies such as foreign keys, unique and primary key constraints, computed columns, indexes)

    CREATE TABLE [dbo].[TestTable]
    (
    A INT DEFAULT '1' CHECK (A=1),
    B INT,
    CHECK (A > B)
    )
    
    GO
    
    DECLARE @TwoPartTableNameQuoted nvarchar(500) = '[dbo].[TestTable]',
            @ColumnNameUnQuoted sysname = 'A',
            @DynSQL NVARCHAR(MAX);
    
    SELECT @DynSQL =
         'ALTER TABLE ' + @TwoPartTableNameQuoted + ' DROP' + 
          ISNULL(' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(c.default_object_id)) + ',','') + 
          ISNULL(check_constraints,'') + 
          '  COLUMN ' + QUOTENAME(@ColumnNameUnQuoted)
    FROM   sys.columns c
           CROSS APPLY (SELECT ' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(referencing_id)) + ','
                        FROM   sys.sql_expression_dependencies
                        WHERE  referenced_id = c.object_id
                               AND referenced_minor_id = c.column_id
                               AND OBJECTPROPERTYEX(referencing_id, 'BaseType') = 'C'
                        FOR XML PATH('')) ck(check_constraints)
    WHERE  c.object_id = object_id(@TwoPartTableNameQuoted)
           AND c.name = @ColumnNameUnQuoted;
    
    PRINT @DynSQL;
    EXEC (@DynSQL); 
    

提交回复
热议问题