1. 程式人生 > >刪除具有約束constraint列的方法---T-sql

刪除具有約束constraint列的方法---T-sql

當刪除一個表中的一個欄位,恰好這個欄位有預設值或是外來鍵等約束的話,直接刪除會報錯

Msg 5074, Level 16, State 1, Line 32
The object 'DF__tmpTblFor__Incre__3D6081D7' is dependent on column 'ExampleColumn'.
Msg 4922, Level 16, State 9, Line 32
ALTER TABLE DROP COLUMN IncreaseApplies failed because
one or more objects access this column.

採用一下sql語句可以完全將此欄位的所有關係刪除並從當前表中刪除此欄位

-- first define variables
declare @default sysname, @sql nvarchar(max)

-- get name of default constraint
select @default = name
from sys.default_constraints
where parent_object_id = object_id('TABLE_NAME')
AND type = 'D'
AND parent_column_id = (
    select column_id
from sys.columns
    where object_id = object_id('TABLE_NAME')
and name = 'COLUMN_NAME'
)

-- create alter table command as string and run it
set @sql = N'alter table TABLE_NAME drop constraint ' + @default
exec sp_executesql @sql

-- now we can finally drop column
ALTER TABLE [TABLE_NAME]
DROP COLUMN COLUMN_NAME