使用FOR XML PATH结果集将子标记添加到XML_VAR中

时间:2017-02-24 11:56:17

标签: sql sql-server xml tsql path

我尝试使用一个独特的查询来获得带有子标记的@xml_var。但是我从来没有为这个国王的结果集做过。有人可以给我一些提示以获得正确的结果吗? Thnaks ALEN,意大利

FROM

 DECLARE @xml_var XML  
    SET @xml_var =  (
                SELECT 
                    nRiga as LineNumber,
                    nRiga as BuyersOrderLineReference,
                    skuFornitore as SuppliersProductCode,
                    '' as BuyersProductCode,
                    FR.quantita as Amount
                FROM Testate FT
                JOIN Righe FR
                       ON (FT.idOrdine = FR.idOrdine AND FR.idStato <> 'A')
                --WHERE FT.idOrdine = @idOrdine
                WHERE ft.idOrdine = 'XXXXXXXXXXXXXX'
                Order by fr.nRiga
                FOR XML PATH('OrderLine')
                )
    SELECT @xml_var

我的结果就像......

<OrderLine>
<LineNumber>1</LineNumber>
<BuyersOrderLineReference>1</BuyersOrderLineReference>
<SuppliersProductCode>PTN-9050</SuppliersProductCode>
<BuyersProductCode />
<Amount>2</Amount>
</OrderLine>

我需要像......

<OrderLine>
    <LineNumber Preserve="true">1</LineNumber>
    <OrderLineReferences>
        <BuyersOrderLineReference Preserve="true">1</BuyersOrderLineReference>
    </OrderLineReferences>
    <Product>
        <SuppliersProductCode>PTN-9050</SuppliersProductCode>
        <BuyersProductCode></BuyersProductCode>
    </Product>
    <Quantity>
        <Amount>2</Amount>
    </Quantity>
</OrderLine>

1 个答案:

答案 0 :(得分:1)

以下硬编码示例返回您似乎需要的XML:

应该很容易从表中获取值。

如果有1:n - 我认为1:1数据的数据......可能会有所不同......

SELECT 'true' AS [LineNumber/@Preserve]
      ,1 AS LineNumber
      ,(
        --I assume this is 1:n
        SELECT 'true' AS [BuyersOrderLineReference/@Preserve]
              ,1 AS BuyersOrderLineReference
        FOR XML PATH('OrderLineReferences'),TYPE
       )   
       ,'PT-9050' AS [Product/SuppliersProductCode]
       ,'' AS [Product/BuyersProductCode]
       ,2 AS [Quantity/Amount]
FOR XML PATH('OrderLine');

结果

<OrderLine>
  <LineNumber Preserve="true">1</LineNumber>
  <OrderLineReferences>
    <BuyersOrderLineReference Preserve="true">1</BuyersOrderLineReference>
  </OrderLineReferences>
  <Product>
    <SuppliersProductCode>PT-9050</SuppliersProductCode>
    <BuyersProductCode></BuyersProductCode>
  </Product>
  <Quantity>
    <Amount>2</Amount>
  </Quantity>
</OrderLine>