1. 程式人生 > >批量更新具有數千屬性列的資料表的記錄資訊(SQL Server 2005)

批量更新具有數千屬性列的資料表的記錄資訊(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)[email protected]表屬性列總數
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

'[email protected]+'=1000 where '[email protected]+'=100')
 set @[email protected]+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

*/