
求大神幫忙看看如何動態實作? 求寫個例子~~~
uj5u.com熱心網友回復:
create table A表
(fdate varchar(10),
張三 int,
李四 int,
王五 int)
insert into A表(fdate,張三,李四,王五)
select '2020-7-1',60,70,65 union all
select '2020-7-2',68,80,88 union all
select '2020-7-3',60,71,65
declare @tsql nvarchar(max)
select @tsql=isnull(@tsql+N',',N'')+N'['+b.name+N']'
from sys.tables a
inner join sys.columns b on a.object_id=b.object_id
where a.name=N'A表' and b.name<>N'fdate'
select @tsql=N'select fdate,col,val
from A表 a
unpivot(val for col in('+@tsql+N')) b '
exec(@tsql)
/*
fdate col val
---------- -------------------- --------------------
2020-7-1 張三 60
2020-7-1 李四 70
2020-7-1 王五 65
2020-7-2 張三 68
2020-7-2 李四 80
2020-7-2 王五 88
2020-7-3 張三 60
2020-7-3 李四 71
2020-7-3 王五 65
(9 行受影響)
*/
uj5u.com熱心網友回復:
關注一下,我也想看看該怎么辦。轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/17865.html
標籤:基礎類
