如何使用带有行项目的SQL PATH模式生成XML

时间:2016-03-01 10:14:16

标签: sql sql-server xml

我正在尝试根据两个SQL表中的数据生成XML字符串。一个包含Order Header数据,另一个包含Line Item数据。

我的问题是我无法将订单项信息正确显示为单个订单中的多个元素:

这是SQL语句:

Select  
                    LTRIM(RTRIM(H.CustPONbr)) As "Transactions/Transaction/CustomerOrdNumber",              
                    (
                    Select LTRIM(RTRIM(InvtID)) As "data()" From X888_Amazon_Order_Line L1 
                    Where L1.CpnyID = H.CpnyID And L1.CustPONbr = H.CustPONbr
                    FOR XML PATH (''), ELEMENTS
                    ) As "Transactions/Transaction/LineItems/LineItem/InvtId"

                From X888_Amazon_Order_Header H (nolock)
                 where h.CustPONbr = '99999014'
                For XML PATH ('ProcessEngineSubmission'), Root ('XML'), ELEMENTS

这是我得到的结果:

<XML>
    <Transactions>
      <Transaction>
        <CustomerOrdNumber>99999014</CustomerOrdNumber>
        <LineItems>
          <LineItem>
            <InvtId>TEST 1235 TEST 1234</InvtId>
          </LineItem>
        </LineItems>
      </Transaction>
    </Transactions>
</XML>

如果我执行内部选择(用InvtId替换“data()”),我得到了我想要实现的目标:

<InvtId>TEST 1235</InvtId>
<InvtId>TEST 1234</InvtId>

1 个答案:

答案 0 :(得分:2)

试试这样:

嵌套选择需要,TYPE扩展名以XML格式返回...

您可能需要在内部PATH('')中指定路径,或使用AS为该列命名...

Select LTRIM(RTRIM(H.CustPONbr)) As "Transactions/Transaction/CustomerOrdNumber"
      ,(
            Select LTRIM(RTRIM(InvtID))  
            From X888_Amazon_Order_Line L1 
            Where L1.CpnyID = H.CpnyID And L1.CustPONbr = H.CustPONbr
            FOR XML PATH (''), TYPE
        ) As "Transactions/Transaction/LineItems/LineItem/InvtId"

From X888_Amazon_Order_Header H (nolock)
where h.CustPONbr = '99999014'
For XML PATH ('ProcessEngineSubmission'), Root ('XML')