如何删除约束列?

如何删除SQL Server 2008中具有默认约束的列?

我的查询是

alter table tbloffers
drop column checkin

我正在低于错误

ALTER TABLE DROP COLUMN checkin失败,因为一个或多个对象访问此列。

任何人都可以纠正我的查询删除约束列?


首先,您应该删除有问题的DEFAULT constraint ,之后您可以删除该列

alter table tbloffers drop constraint [ConstraintName]
go

alter table tbloffers drop column checkin

但是这个错误可能会出于其他原因 - 例如用户定义的函数或为其设置了SCHEMABINDING选项的视图。

UPD:完全自动删除约束脚本:

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

这里有另一种方法可以用一个未知名称删除默认约束,而不必先运行一个单独的查询来获取约束名称:

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)

在这里查询这个查询的默认约束:

SELECT
    df.name 'Constraint Name' ,
    t.name 'Table Name',
    c.NAME 'Column Name'
FROM sys.default_constraints df
INNER JOIN sys.tables t ON df.parent_object_id = t.object_id
INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id

这给你默认约束的名称,以及表和列的名称。

当你有这些信息时,你需要首先删除默认约束:

ALTER TABLE dbo.YourTable
DROP CONSTRAINT name-of-the-default-constraint-here

然后你可以删除该列

ALTER TABLE dbo.YourTable DROP COLUMN YourColumn
链接地址: http://www.djcxy.com/p/76319.html

上一篇: How to drop column with constraint?

下一篇: Add a column if it doesn't exist to all tables?