How to drop column with constraint?

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

    Here's another way to drop a default constraint with an unknown name without having to first run a separate query to get the constraint name:

    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 = N'__ColumnName__'
                            AND object_id = OBJECT_ID(N'__TableName__'))
    IF @ConstraintName IS NOT NULL
    EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
    

提交回复
热议问题