批量修改數據庫中字段的數據類型

在有些時候,需要將某種數據類型的字段,修改爲另一種數據類型,可使用下列腳本實現;例如:原來定義爲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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章