0

我正在尝试构建一些查询来导出 XML 中的数据,并构建了这个查询:

select
    [invoice].*,
    [rows].*,
    [payment].payerID,
    [items].picture
from InvoicesHeader [invoice]
join InvoicesRows   [rows]      on  [rows].invoiceID=[invoice].invoiceID 
join Payments       [payments]  on  [payments].paymentID=[invoice].paymentID
join Items          [items]     on  [items].itemID=[rows].itemID
FOR XML Auto, ROOT ('invoices'), ELEMENTS

结果我得到了这样的东西

<invoices>    
    <invoice>
        <ID>82</ID>
        <DocType>R</DocType>
        <DocYear>2017</DocYear>
        <DocNumber>71</DocNumber>
        <IssueDate>2017-07-17T15:17:30.237</IssueDate>
        <OrderID>235489738019</OrderID>
        ...
        <payments>
            <payerID>3234423f33</payerID>
            <rows>
                <ID>163</ID>
                <ItemID>235489738019</ItemID>
                <Quantity>2</Quantity>
                <Price>1</Price>
                <VATCode>22</VATCode>
                <Color>-</Color>
                <Size></Size>
                <SerialNumber></SerialNumber>
                <items>
                    <picture>http://nl.imgbb.com/AAOSwOdpXyB4I.JPG</picture>
                </items>
            </rows>
            ....

        </payments>
    </invoice>
</invoices>

虽然我想在哪里有这样的东西

[rows] 是发票的子节点,而不是付款的子节点

<invoices>    
    <invoice>
        <ID>82</ID>
        <DocType>R</DocType>
        <DocYear>2017</DocYear>
        <DocNumber>71</DocNumber>
        <IssueDate>2017-07-17T15:17:30.237</IssueDate>
        <OrderID>235489738019</OrderID>
        ...
        <payments>
            <payerID>3234423f33</payerID>
        </payments>
        <rows>
            <ID>163</ID>
            <ItemID>235489738019</ItemID>
            <Quantity>2</Quantity>
            <Price>1</Price>
            <VATCode>22</VATCode>
            <Color>-</Color>
            <Size></Size>
            <SerialNumber></SerialNumber>
            <items>
                <picture>http://nl.imgbb.com/AAOSwOdpXyB4I.JPG</picture>
            </items>
        </rows>
            ....
    </invoice>
</invoices>

看到了一些有很多的解决方案

对于 XML 自动

放在一起,但是这里的数据来自连接表,很遗憾重新查询2-3次相同的值

怎样才能实现呢?

谢谢

4

2 回答 2

0

好吧,发现必须改用FOR XML PATH另一个表作为子查询,每个表FOR XML PATH如下:

select
[invoice].*,
p.payerID,
(select r.* from InvoiceRows r where r.invoiceID=i.invoiceID for XML PATH ('rows'), type)
from InvoicesHeader i
join payment        p on i.paymentID=p.paymentID
FOR XML PATH('invoice'), ROOT ('invoices'), ELEMENTS
于 2017-08-13T03:45:12.160 回答
0

尝试将选择顺序更改为此;

select
    [invoice].*,
    [payment].payerID,
    [items].picture,
    [rows].*

from InvoicesHeader [invoice]
join InvoicesRows   [rows]      on  [rows].invoiceID=[invoice].invoiceID 
join Payments       [payments]  on  [payments].paymentID=[invoice].paymentID
join Items          [items]     on  [items].itemID=[rows].itemID
FOR XML Auto, ROOT ('invoices'), ELEMENTS
于 2017-07-17T14:07:29.500 回答