当前位置: 移动技术网 > IT编程>数据库>MSSQL > 将数据库某种类型的字段更新为另一种类型

将数据库某种类型的字段更新为另一种类型

2019年07月21日  | 移动技术网IT编程  | 我要评论

欧莱雅发膜怎么样,赫斯特皇家贵族学院,图片网站程序

有时,我们可能会遇到这样的情况,当我们数据表的float类型精度不够时,可能需要把它统一调整成decimal或者money,而这时你一个一个去修改可能会崩溃,因为你无法从几千张表里确实找到所有的float类型的字段,而这时我们就需要自动的,批量的去处理它们。

实现思路:从系统表中查询所有用户建立的表,然后查询指定类型的所有字段,最后使用alter table alter column去更新这个字段.

知识点

  1. 游标
  2. exec
  3. sysobjects表和syscolumns表

常用类型的typeid值

 xtype= 35 'text' 
 xtype=36 'uniqueidentifier' 
 xtype=48 'tinyint' 
 xtype=52 'smallint' 
 xtype=56 'int' 
 xtype=58 'smalldatetime' 
 xtype=59 'real' 
 xtype=60 'money' 
 xtype=61 'datetime' 
 xtype=62 'float' 
 xtype=98 'sql_variant' 
 xtype=99 'ntext' 
 xtype=104 'bit' 
 xtype=106 'decimal' 
 xtype=108 'numeric' 
 xtype=122 'smallmoney' 
 xtype=127 'bigint' 
 xtype=165 'varbinary' 
 xtype=167 'varchar'
 xtype=173 'binary' 
 xtype=175 'char' 
 xtype=189 'timestamp' 
 xtype=231 'nvarchar'
 xtype=239 'nchar' 
 xtype=241 'xml' 
 xtype=231 'sysname'

实现代码

declare @tablename varchar(256)
declare @columnname varchar(256)
declare cursor2 cursor
for
select name from sysobjects where type='u'
open cursor2
fetch next from cursor2 into @tablename
while @@fetch_status = 0  
    begin
declare cursor3 cursor
for                       
select name from syscolumns where id=object_id(@tablename) and xtype=60
open cursor3
fetch next from cursor3 into @columnname
while @@fetch_status = 0  
    begin
        print '更新表'+@tablename+',更新字段'+@columnname
         
    exec('alter table '+@tablename+' alter column '+@columnname+' [float] ')
    
        fetch next from cursor3 into @columnname
    end
close cursor3
deallocate cursor3

        fetch next from cursor2 into @tablename
    end
close cursor2
deallocate cursor2

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网