用于xml路径的T-sql

时间:2012-09-20 15:40:27

标签: sql tsql xpath

我有一个具有以下结构的表 的OrderItems

    OrderId  ProductName  UnitPrice
      1      Harley         1.0
      1      Gloves         0.25
      2      Gloves         0.25


 By doing a select I would like to obtain something similar with :
<Order>
<OrderItem>
<OrderId>1</OrderId><ProductName>Harley</ProductName><UnitPrice>1.0</UnitPrice>
</OrderItem>
<OrderItem>
<OrderId>1</OrderId><ProductName>Gloves</ProductName><UnitPrice>0.25</UnitPrice>
</OrderItem>
</Order>

and 
<Order>
<OrderItem>
<OrderId>2</OrderId><ProductName>Gloves</ProductName><UnitPrice>0.25</UnitPrice>
</OrderItem>
</Order>

目前我被困在

SELECT 
  t2.OrderId, t2.ProductName, t2.UnitPrice  
       FROM OrderItems t2,OrderItems t1 where t2.OrderId = t1.OrderId
        FOR XML PATH('OrderItem') , ROOT('Order')

1 个答案:

答案 0 :(得分:2)

这个

DECLARE @OrderItems TABLE (OrderID INT, ProductName VARCHAR(50), UnitPrice MONEY)
INSERT @OrderItems VALUES (1, 'Harley', 1.0), (1, 'Gloves', 0.25), (2, 'Gloves', 0.25)

SELECT  (   SELECT  OrderID, ProductName, UnitPrice
            FROM    @OrderItems t2
            WHERE   t2.OrderID = t1.OrderID
            FOR XML PATH('OrderItem'), TYPE
        ) 
FROM    (SELECT DISTINCT OrderID FROM @OrderItems) t1 
FOR XML PATH('Order') , ROOT('Orders')

提供此输出

<Orders>
  <Order>
    <OrderItem>
      <OrderID>1</OrderID>
      <ProductName>Harley</ProductName>
      <UnitPrice>1.0000</UnitPrice>
    </OrderItem>
    <OrderItem>
      <OrderID>1</OrderID>
      <ProductName>Gloves</ProductName>
      <UnitPrice>0.2500</UnitPrice>
    </OrderItem>
  </Order>
  <Order>
    <OrderItem>
      <OrderID>2</OrderID>
      <ProductName>Gloves</ProductName>
      <UnitPrice>0.2500</UnitPrice>
    </OrderItem>
  </Order>
</Orders>

我认为这就是你所追求的目标。

<强> SQL Fiddle