MSSQL如何刪除有預設值的欄位

MSSQL刪除有預設值的欄位看起來不是像MYSQL那樣下一行ALERT TABLE DROP COLUMN指令這麼簡單就可以,它會跳出該欄位物件有被Constraint使用,且無法被刪除的警告。如果是使用SQL Management Studio也許它會幫你處理好這個問題,但如果是透過其他SQL工具或是程式刪除的話,可能就沒這麼容易。爬了一下文(參考),下面這段SQL解決了這個問題,只需要取代__TableName__和__ColumnName__為想要刪除表的名稱和欄位名稱即可。

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)
IF EXISTS (SELECT * FROM syscolumns WHERE id=object_id('__TableName__') AND name='__ColumnName__')
EXEC('ALTER TABLE __TableName__ DROP COLUMN __ColumnName__')

除了欄位有預設值會遇到這問題外,當該欄位有FK或其他Constraint的時候,也可以試試下面的程式碼:

IF EXISTS(SELECT 1 FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__')
BEGIN
SELECT @ConstraintName = CONSTRAINT_NAME FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE where TABLE_NAME = '__TableName__' AND COLUMN_NAME = '__ColumnName__'
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)
END

 

 

Leave a Reply

當第一個留言者!

avatar
wpDiscuz