mssql按字段名称删除约束

时间:2022-10-09 16:16:17
DECLARE @TableName AS NVARCHAR(255),
     @ColumnName AS NVARCHAR(255),
     @ConstraintName AS NVARCHAR(255),
     @DropConstraintSQL AS NVARCHAR(255)


SET @TableName = 'tb_part'
SET @ColumnName = 'partdifficult'


--Get the name of the constraint that will be dropped
SET @ConstraintName = 
     (SELECT TOP 1 o.name FROM sysobjects o 
     JOIN syscolumns c 
     ON o.id = c.cdefault 
     JOIN sysobjects t 
     ON c.id = t.id 
     WHERE o.xtype = 'd' 
     AND c.name = @ColumnName 
     AND t.name = @TableName)


--Build a query string that will drop the constraint
SET @DropConstraintSQL = 'ALTER TABLE ' + @TableName + ' DROP ' + @ConstraintName


--Execute the sql to drop the constraint
EXEC (@DropConstraintSQL)


GO