id name Number A1 A2 A3......A40 (一条记录)
1 jick 40 05 01 02 11 (记录中的值)
我想把这一条记录改写成下面这个样子的一个表
id name Number AA
1 jick 40 05
2 jick 40 01
3 jick 40 02
.
.
.
.
40 jick 40 40
------解决方案--------------------
drop table tbtest
go
create table tbtest(id int,name varchar(10),Number int,A1 varchar(10),A2 varchar(10),A3 varchar(10),A40 varchar(10))
insert into tbtest
select 1, 'jack ',40, '05 ', '01 ', '02 ', '11 '
declare @sql varchar(8000)
set @sql= ' '
select @[email protected]+ 'union all '+char(13)+ 'select name,Number, '+name+ ' as [AA] from tbtest '+char(13)
from syscolumns
where id=object_id( 'tbtest ') and name not in ( 'id ', 'name ', 'Number ')
select @sql= 'select id=identity(int,1,1),* into #t from( '+stuff(@sql,1,len( 'union all ')+1, ' ')+ ')t '+char(13)+ 'select * from #t '
exec(@sql)
/*
(所影响的行数为 4 行)
id name Number AA
----------- ---------- ----------- ----------
1 jack 40 05
2 jack 40 01
3 jack 40 02
4 jack 40 11
*/