我正在尝试生成一些具有各种嵌套级别的XML,并且存在过度简化的风险,输出XML将大致采用以下格式:
<invoice number="1">
<charge code="foo" rate="123.00">
<surcharge amount="10%" />
</charge>
<charge code="bar" />
</invoice>
我为此继承的数据库模式恰好将费用存储在不同的表中,这意味着根据收费来自的表格,附加费的存储方式不同。
鉴于你cannot use UNION
s with FOR XML
,我在CTE中做了一些UNION
,所以有以下几点:
WITH Charges ( [@code], [@rate], surcharge, InvoiceId ) AS (
SELECT code AS [@Code], amount AS [@rate], NULL as surcharge, InvoiceId
FROM item.charges
UNION ALL
SELECT
code AS [@Code],
amount AS [@rate],
(
SELECT amount AS [@amount]
FROM order.surcharges os
WHERE oc.ChargeId = os.ChargeId
FOR XML PATH('surcharge'), TYPE
),
InvoiceId
FROM order.charges oc
)
SELECT
Number AS [@number],
(
SELECT
[@code],
[@rate],
surcharge
FROM Charges
WHERE Charges.InvoiceId = i.InvoiceId
)
FROM Invoices i
FOR XML PATH( 'invoice' ), TYPE
现在,令人难以置信地关闭,给出(注意嵌套的<surcharge>
):
<invoice number="1">
<charge code="foo" rate="123.00">
<surcharge>
<surcharge amount="10%" />
</surcharge>
</charge>
<charge code="bar" />
</invoice>
但我需要找到一种方法来获取结束查询,以包含要被视为元素内容的XML列的值,而不是作为新元素。这是可能的,还是我需要采取新的方法?
答案 0 :(得分:1)
你有一个列查询,它返回多行(@ charge,@rate和XML类型。)我希望你发布的查询给出错误:
只能指定一个表达式 在子查询中的选择列表中 没有引入EXISTS。
但是,通过将查询移至outer apply
可以轻松解决此问题。要删除双surcharge
元素,您可以将XML列名称尽可能地移动到底部,例如:
;WITH Charges (code, rate, surcharge, InvoiceId) AS
(
SELECT code, amount, NULL, InvoiceId
FROM @charges
UNION ALL
SELECT code
, amount
, (
SELECT amount AS [@amount]
FROM @surcharges os
WHERE oc.ChargeId = os.ChargeId
FOR XML PATH('surcharge'), TYPE
)
, InvoiceId
FROM @charges oc
)
SELECT Number AS [@number]
, c.code as [charge/@code]
, c.rate as [charge/@rate]
, c.surcharge as [charge]
FROM @Invoices i
outer apply
(
SELECT code
, rate
, surcharge
FROM Charges
WHERE Charges.InvoiceId = i.InvoiceId
) c
WHERE i.InvoiceID = 1
FOR XML PATH( 'invoice' ), TYPE
这将打印,例如:
<invoice number="1">
<charge code="1" rate="1" />
</invoice>
<invoice number="1">
<charge code="1" rate="1">
<surcharge amount="1" />
</charge>
</invoice>
第一个元素来自联合的顶部,surcharge = null
。
答案 1 :(得分:1)
似乎将(假)列命名为“*”将使用该列的内容作为元素的内容,因此更改SQL如下所示:
WITH Charges ( [@code], [@rate], surcharge, InvoiceId ) AS (
SELECT code AS [@Code], amount AS [@rate], NULL as surcharge, InvoiceId
FROM item.charges
UNION ALL
SELECT
code AS [@Code],
amount AS [@rate],
(
SELECT amount AS [@amount]
FROM order.surcharges os
WHERE oc.ChargeId = os.ChargeId
FOR XML PATH('surcharge'), TYPE
),
InvoiceId
FROM order.charges oc
)
SELECT
Number AS [@number],
(
SELECT
[@code],
[@rate],
surcharge AS [*] -- Thsi will embed the contents of the previously generated XML in here.
FROM Charges
WHERE Charges.InvoiceId = i.InvoiceId
)
FROM Invoices i
FOR XML PATH( 'invoice' ), TYPE
答案 2 :(得分:0)
我认为您可以通过省略“for xml path('surcharge')”语句中的根节点类型来实现此目的。也就是说,改为使用“for xml path('')”。