删除时需要确保表和列存在,如果有限制先删除限制再删除列。
IF EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(N'TableName') AND NAME = N'ColumnName') BEGIN DECLARE @CONS_NAME sysname; SELECT @CONS_NAME = OBJECT_NAME(default_object_id) FROM sys.columns WHERE [object_id] = OBJECT_ID('TableName') AND name = 'ColumnName'; IF @CONS_NAME IS NOT NULL AND LEN(@CONS_NAME) > 0 BEGIN EXEC ('ALTER TABLE TableName DROP CONSTRAINT ' + @CONS_NAME); END Alter Table TableName DROP COLUMN ColumnName; END
使用GO分割,删除多个列时,可以使用相同的参数名称。
GO