批量更新具有数千属性列的数据表的记录信息(SQL Server 2005)

/*
需求:在SQL2005中有一个表,数千属性列,现在需要把各属性列中所有的100改为1000,用 update 改需要给出列名,可是有数千列,又不可能都列出。

解决思路:把表的属性列名放入一个表中,然后遍历表名逐列进行 update 更新操作

*/

--以实例作解:

--------------------SQL Server数据格式化工具-------------------
---------------------------------------------------------------
-- DESIGNER :happycell188(喜喜)
--       QQ :584738179
-- Development Tool :Microsoft Visual C++ 6.0    C Language
-- FUNCTION :CONVERT DATA TO T-SQL
---------------------------------------------------------------
-- Microsoft SQL Server  2005
-- Developer Edition on Microsoft Windows XP [版本 5.1.2600]
---------------------------------------------------------------
---------------------------------------------------------------

use test
go
if object_id('test.dbo.tb') is not null drop table tb
--创建数据表
create table tb(a int,b int,c int,d int,e int,f int,g int)
go
--插入测试数据
insert into tb select 100,59,300,100,100,1000,243
union all select 102,2000,45,100,345,100,100
union all select 20,100,100,100,353,543,5435
go
--代码实现
select * from tb
/*原数据记录

a  b  c  d  e  f  g
------------------------------------
100 59 300 100 100 1000 243
102 2000 45 100 345 100 100
20 100 100 100 353 543 5435

*/
--代码实现阶段
declare @total_col_num int,@i int,@col varchar(30)--@num表属性列总数
declare @temp_col_table table(id int identity(1,1),name varchar(100))--创建临时表存储属性列信息
insert into @temp_col_table select name from SysColumns where id=Object_Id('tb')
select top 1 @total_col_num=id,@i=1 from @temp_col_table order by id desc--获取属性列总个数
while(@i<@total_col_num)
begin
 select top 1 @col=name from @temp_col_table where name not in (select top (@i-1) name from @temp_col_table)
 exec('update tb set '+@col+'=1000 where '+@col+'=100')
 set @i=@i+1
end
select * from tb
/* 批量update后的数据记录

a  b  c  d  e  f  g
---------------------------------------------
1000 59 300 1000 1000 1000 243
102 2000 45 1000 345 1000 100
20 1000 1000 1000 353 543 5435

*/

猜你喜欢

转载自blog.csdn.net/happycell188/article/details/5498545