我正在尝试连接三个表以便将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 :(得分: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')