批量修改SQL数据库表中 某字段的默认值 的语句 谢谢

2024-11-05 04:06:07
推荐回答(1个)
回答1:

----先删除要处理字段的默认值约束
declare @s varchar(8000)
set @s=''
select @s=@s+'
alter table ['+b.name+'] drop constraint ['+d.name+']'
from syscolumns a
join sysobjects b on a.id=b.id
join syscomments c on a.cdefault=c.id
join sysobjects d on c.id=d.id
where b.name='KeyWords'
and (a.name='hits')
exec(@s)

----如果要要将 hits 字段改为数字类型
alter table KeyWords alter column [hits] numeric(18,0)

----再为字段 hits 添加默认值约束
set @s='alter table KeyWords add constraint
[df__t1__hits__'+cast(newid() as varchar(36))
+'] default (0) for hits'
exec(@s)
go

--如果要改已有的数据
update KeyWords set hits=0 where 1=1