SQL批量删除数据表中指定字段对应的所有约束
--SQL批量删除数据表中指定字段对应的所有约束
--定义要操作的数据表名变量
declare @TableName nvarchar(250)
set @TableName='数据表名'
--定义要操作的字段名变量
declare @ColumnName nvarchar(250)
set @ColumnName='字段名'
--定义当前查询的约束变量
declare @ConstraintName varchar (250)
--声明读取数据表中指定字段对应的所有约束列表游标
declare mycursor cursor for select name from sysobjects left join sysconstraints on sysconstraints.constid=sysobjects.id where parent_obj=OBJECT_ID(''+@TableName+'') and colid=(select colid from syscolumns where id=OBJECT_ID(''+@TableName+'') and OBJECTPROPERTY(id, N'IsUserTable') = 1 and upper(name)=upper(@ColumnName))
--打开游标
open mycursor
--从游标里取出数据赋值到主键约束名称变量中
fetch next from mycursor into @ConstraintName
--如果游标执行成功
while (@@fetch_status=0)
begin
--删除当前找到的约束
--print '当前删除语句'+'ALTER TABLE ['+@TableName+'] DROP CONSTRAINT ['+@ConstraintName+']'
exec ('ALTER TABLE ['+@TableName+'] DROP CONSTRAINT ['+@ConstraintName+']')
print '已成功删除数据表['+@TableName+']字段['+@ColumnName+']对应的约束['+@ConstraintName+']'
--用游标去取下一条记录
fetch next from mycursor into @ConstraintName
end
--关闭游标
close mycursor
--撤销游标
deallocate mycursor
--以上程序已测试:测试环境Windows2003+SQL2008 SERVER R2