How to drop column with constraint?

后端 未结 8 587
半阙折子戏
半阙折子戏 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条回答
  •  半阙折子戏
    2020-11-29 17:33

    First you should drop the problematic DEFAULT constraint, after that you can drop the column

    alter table tbloffers drop constraint [ConstraintName]
    go
    
    alter table tbloffers drop column checkin
    

    But the error may appear from other reasons - for example the user defined function or view with SCHEMABINDING option set for them.

    UPD: Completely automated dropping of constraints script:

    DECLARE @sql NVARCHAR(MAX)
    WHILE 1=1
    BEGIN
        SELECT TOP 1 @sql = N'alter table tbloffers drop constraint ['+dc.NAME+N']'
        from sys.default_constraints dc
        JOIN sys.columns c
            ON c.default_object_id = dc.object_id
        WHERE 
            dc.parent_object_id = OBJECT_ID('tbloffers')
        AND c.name = N'checkin'
        IF @@ROWCOUNT = 0 BREAK
        EXEC (@sql)
    END
    

提交回复
热议问题