SQL Server - 如何将查询和子查询结果组合在FOR XML PATH T-SQL查询中的单个节点中

时间:2014-07-11 18:08:08

标签: sql sql-server xml tsql

我想要以下输出

<a>
 <b>
  <c>
   <customer>Miller</customer> 
   <d id="21">Bike</d> 
   <d id="22">Helmete</d> 
  </c>
 </b>
</a>

我尝试了以下查询(从另一个stackexchange页面被盗并修改)

--Table for demo
declare @OrderTbl table ( id int, customer nvarchar(100))

declare @OrderDetail table ( ID int, fk_Order int,Item nvarchar(100))

--Load some data
insert into @OrderTbl select 1, 'Miller'

insert into @OrderDetail select 21 ,1,'Bike'
union all select 22 ,1,'Helmete'
union all select 23 ,2,'Bike'
union all select 24 ,2,'Helmete'

select 
 a.customer as "c/customer"
, (  select b.ID as "@id"
    , b.Item AS "data()"
  from @OrderDetail b 
  where a.id = b.fk_Order
  for xml path('d'),root('c'),type
)
from @OrderTbl a
for xml path('b'),root('a')

但它给了我以下

<a>
 <b>
  <c>
   <customer>Miller</customer>
  </c>
  <c>
  <d id="21">Bike</d>
  <d id="22">Helmete</d>
  </c>
 </b>
</a>

我现在把它搞砸了 将查询结果转换为varchar并替换

"</c><c>" 

""

但至少可以说,这是非常不优雅的。任何人都可以提出更好的方法吗?

1 个答案:

答案 0 :(得分:0)

你非常接近。只需将[客户]放在查询的一个级别,从b到c

  SELECT (
    SELECT
      [customer]
     ,( SELECT
          [id] AS [@id],
          [Item] AS [data()]
        FROM @OrderDetail od
        WHERE od.fk_Order = ot.id
        FOR XML PATH('d'),TYPE
      )
    FROM @OrderTbl ot
    FOR XML PATH('c'),TYPE
  ) FOR XML PATH('b'), ROOT('a')