假设我有一个定义为这样的表:
CREATE TABLE #TmpExampleTable
(
id int identity(0,1),
method_id int,
entity_id int
)
并且将示例数据添加到表中,select *返回:
id method_id entity_id
0 105 39
1 105 43
2 9 92
3 9 572
4 9 1014
5 9 1427
6 9 1959
7 9 2266
我想转换从以下select语句返回的结果:
select method_id,entity_id from #TmpExampleTable
method_id entity_id
105 39
105 43
9 92
9 572
9 1014
9 1427
9 1959
9 2266
这样的事情:
method_id entities
105 <Entities><Entity id=39 /><Entity id=43 /></Entities>
9 <Entities><Entity id=572 /><Entity id=1014 /><Entity id=1427 /><Entity id=1959 /><Entity id=2266 /></Entities>
这甚至可能吗?我已经尝试过各种CTE和FOR XML语句的组合,但是无法按照我想要的方式进行格式化。
答案 0 :(得分:1)
这是怎么回事?
CREATE TABLE #TmpExampleTable
(
id int identity(0,1),
method_id int,
entity_id int
)
INSERT #TmpExampleTable (method_id, entity_id) VALUES
(105 , 39 ),
(105 , 43 ),
(9 , 92 ),
(9 , 572 ),
(9 , 1014),
(9 , 1427),
(9 , 1959),
(9 , 2266)
select method_id, (select entity_id as '@id' from #TmpExampleTable WHERE (method_id = results.method_id) for xml path('Entity'), root('Entities'),TYPE)
from #TmpExampleTable results
group by method_id
drop table #tmpexampletable