批量更新具有数千属性列的数据表的记录信息(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

*/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜-喜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值