学习存储过程列转行
0)列转行。注意:列多少不限,名称未知。
1)有什么

2)要什么
3)参考代码
--列转行。新写法。
--注意:比unpivot更灵活,支持字段名实现未知的情况。
with TestData as (
select 1 as id, 1 as f1, 2 as f2, 3 as f3, 4 as f4
union all
select 2 as id, 7 as f1, 8 as f2, 9 as f3, 10 as f4
)
select x0.id, x2.k, x2.v
from TestData x0
outer apply (
select cast((
select x.*
from TestData x
where x.id = x0.id
for xml path ('x')
) as xml) as row
) x1
outer apply (
select *
from (
select t.v.value('local-name(.)', 'nvarchar(max)') as k,
cast(t.v.value('.', 'nvarchar(max)') as int) as v
from x1.row.nodes('x/*') t(v)
) y
where y.k <> 'id'
) x2

浙公网安备 33010602011771号