批量修改数据库中字段的数据类型

在有些时候,需要将某种数据类型的字段,修改为另一种数据类型,可使用下列脚本实现;例如:原来定义为decimal(18,2)类型的所有统一修改为decimal(19,4)。
– 关闭 约束
declare tb cursor for
SELECT sql=’alter table [‘+d.name+’] NOCHECK CONSTRAINT all’
FROM syscolumns a left join systypes b on a.xtype=b.xusertype
inner join sysobjects d on a.id=d.id and d.xtype=’U’ and d.name<>’dtproperties’
where b.name in(‘decimal’) GROUP BY d.name
declare @sql1 varchar(1000)
open tb
fetch next from tb into @sql1
while @@fetch_status = 0
begin
print @sql1
exec(@SQL1)
fetch next from tb into @sql1
end
close tb
deallocate tb

-- 修改字段数据类型

declare tb cursor for
SELECT sql=’alter table [‘+d.name+’] alter column [‘+a.name+’] decimal(19,4)’
FROM syscolumns a left join systypes b on a.xtype=b.xusertype
inner join sysobjects d on a.id=d.id and d.xtype=’U’ and d.name<>’dtproperties’
where b.name in(‘decimal’) order by d.name,a.name
declare @sql2 varchar(1000)
open tb
fetch next from tb into @sql2
while @@fetch_status = 0
begin
print @sql2
exec(@SQL2)
fetch next from tb into @sql2
end
close tb
deallocate tb

-- 恢复 约束

declare tb cursor for
SELECT sql=’alter table [‘+d.name+’] CHECK CONSTRAINT ALL’
FROM syscolumns a left join systypes b on a.xtype=b.xusertype
inner join sysobjects d on a.id=d.id and d.xtype=’U’ and d.name<>’dtproperties’
where b.name in(‘decimal’) GROUP BY d.name
declare @sql3 varchar(1000)
open tb
fetch next from tb into @sql3
while @@fetch_status = 0
begin
print @sql3
exec(@SQL3)
fetch next from tb into @sql3
end
close tb
deallocate tb

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值