How to drop column with constraint?

后端 未结 8 578
半阙折子戏
半阙折子戏 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:36

    I got the same:

    ALTER TABLE DROP COLUMN failed because one or more objects access this column message.

    My column had an index which needed to be deleted first. Using sys.indexes did the trick:

    DECLARE @sql VARCHAR(max)
    
    SELECT @sql = 'DROP INDEX ' + idx.NAME + ' ON tblName'
    FROM sys.indexes idx
    INNER JOIN sys.tables tbl ON idx.object_id = tbl.object_id
    INNER JOIN sys.index_columns idxCol ON idx.index_id = idxCol.index_id
    INNER JOIN sys.columns col ON idxCol.column_id = col.column_id
    WHERE idx.type <> 0
        AND tbl.NAME = 'tblName'
        AND col.NAME = 'colName'
    
    EXEC sp_executeSql @sql
    GO
    
    ALTER TABLE tblName
    DROP COLUMN colName
    

提交回复
热议问题