我有下表
Id Name member
1,2,3 Ab,Xy,Pq member1
8,9 De,Fg member2
我想在sql server 2008中使用如下的临时表
Id Name member
1 Ab member1
2 Xy member1
3 Pq member1
8 De member2
9 Fg member1
编辑:请检查我的表有两列逗号分隔值,对于那些值,我需要在最后一个表中显示结果。 1表示Ab,2表示Xy,依此类推。
答案 0 :(得分:1)
尝试以下查询
declare @t table (id varchar(20),name varchar(20),member varchar(20))
insert into @t (id,Name,member) values
('1,2,3', 'Ab,Xy,Pq', 'member1'),
('8,9' , 'De,Fg' , 'member2')
;with t as (select row_number() over (order by member) r, t.member,a.b.value('.','varchar(10)') n from
(select member, cast('<t>'+ replace(id,',','</t><t>')+'</t>' as xml) as id,cast('<t>'+ replace(name,',','</t><t>')+'</t>' as xml) as nme from @t) t
cross apply id.nodes('/t') a(b) ),
t1 as (select row_number() over (order by member) r,a.b.value('.','varchar(10)') n1 from
(select member, cast('<t>'+ replace(id,',','</t><t>')+'</t>' as xml) as id,cast('<t>'+ replace(name,',','</t><t>')+'</t>' as xml) as nme from @t) t
cross apply nme.nodes('/t') a(b))
select t.member,t.n,t1.n1 from t inner join t1 on t.r=t1.r