SqlServer 删除字段约束

declare @tbname sysname,@fdname sysname
select @tbname='s_orderPrintLog' --要处理的表名
,@fdname='PrintCount' --要处理的字段名

--定义删除处理的语句
declare tb cursor local for
--默认值约束
select sql='alter table ['+b.name+'] drop constraint ['+d.name+']'
from syscolumns a
join sysobjects b on a.id=b.id and a.name=@fdname and b.name=@tbname 
join syscomments c on a.cdefault=c.id
join sysobjects d on c.id=d.id
union --外键引用
select s='alter table ['+c.name+'] drop constraint ['+b.name+']'
from sysforeignkeys a
join sysobjects b on b.id=a.constid
join sysobjects c on c.id=a.fkeyid
join syscolumns d on d.id=c.id and a.fkey=d.colid and d.name=@fdname
join sysobjects e on e.id=a.rkeyid and e.name=@tbname
join syscolumns f on f.id=e.id and a.rkey=f.colid 
union --主键/唯一键/索引
select case when e.xtype in('PK','UQ') then 'alter table ['+c.name+'] drop constraint ['+e.name+']'
else 'drop index ['+c.name+'].['+a.name+']' end
from sysindexes a
join sysindexkeys b on a.id=b.id and a.indid=b.indid
join sysobjects c on b.id=c.id and c.xtype='U' and c.name=@tbname
join syscolumns d on b.id=d.id and b.colid=d.colid and d.name=@fdname
left join sysobjects e on e.id=object_id(a.name)
where a.indid not in(0,255)

--执行删除
declare @s varchar(8000)
open tb
fetch next from tb into @s
while @@fetch_status=0
begin
exec(@s)
fetch next from tb into @s
end
close tb
deallocate tb 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值