2015-06-29 91 views
2

我試圖加入一個SQL查詢三個表來輸出格式爲XML 下面是我的查詢:SQL到XML格式化

select 
    invoices.order_no as "order", 
    customerinfo.name as BillingCompanyName, 
    line.item_code, 
    line.item_qty 
from 
    invoices 
inner join 
    customerinfo on customerinfo.cust_code = invoices.cust_code 
inner join 
    line on line.order_no = invoices.order_no 
where 
    invoices.custlog10 = 'f' and invoices.order_no = '332504' 
for xml auto, type, elements 

,這裏是生成的輸出

<invoices> 
    <order>332504</order> 
    <customerinfo> 
    <BillingCompanyName>Two Bear Farm</BillingCompanyName> 
    <line> 
     <item_code>2909-B</item_code> 
     <item_qty>2.000000</item_qty> 
    </line> 
    <line> 
     <item_code>SH-DISC</item_code> 
     <item_qty>1.000000</item_qty> 
    </line> 
    </customerinfo> 
</invoices> 

此輸出大多數情況下,我只是用於移動customerinfo標記結束的位置,如下面以粗體顯示:

<invoices> 
    <order>332504</order> 
    <customerinfo> 
    <BillingCompanyName>Two Bear Farm</BillingCompanyName> 
    </customerinfo> 
    <line> 
     <item_code>2909-B</item_code> 
     <item_qty>2.000000</item_qty> 
    </line> 
    <line> 
     <item_code>SH-DISC</item_code> 
     <item_qty>1.000000</item_qty> 
    </line> 
</invoices> 

此代碼旨在提供給第三方模塊以讀取銷售訂單。

我是新來的SQL輸出作爲XML和解決此格式問題的任何幫助將是太棒了!

回答

0

這樣做的一種方式是通過相關查詢與,你可以採取更多的控制權格式顯式路徑:

select 
    invoices.order_no as "order", 

    (select customerinfo.name as 'BillingCompanyName' 
    from customerinfo where 
    customerinfo.cust_code=invoices.cust_code 
    for xml path('customerinfo'), type, elements 
    ), 

    (select line.item_code, line.item_qty 
    from line where line.order_no = invoices.order_no 
    for xml path('line'), type, elements) 
from 
    invoices 
where 
    invoices.custlog10 = 'f' and invoices.order_no = '332504' 
for xml path('invoices') 

SQLFIDDLE

+0

PERFECTO!謝謝,它像夢一樣工作! – user2379391