tsql – 如何将CTE与FOR XML子句结合使用?

我正在尝试生成一些具有各种嵌套级别的
XML,并且存在过度简化的风险,输出XML将是以下格式:

<invoice number="1">
 <charge code="foo" rate="123.00">
  <surcharge amount="10%" />
 </charge>
 <charge code="bar" />
</invoice>

我为此继承的数据库模式恰好将费用存储在不同的表中,这意味着根据收费来自的表格不同地存储附加费.

鉴于你cannot use UNIONs with FOR XML,我在CTE中完成了一些UNIONing,所以有以下几点:

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

现在,这非常接近,给出(注意嵌套 ):

<invoice number="1">
 <charge code="foo" rate="123.00">
  <surcharge>
   <surcharge amount="10%" />
  </surcharge>
 </charge>
 <charge code="bar" />
</invoice>

但我需要找到一种方法来获取结束查询,以包含要被视为元素内容的XML列的值,而不是作为新元素.这是可能的,还是我需要采取新的方法?

最佳答案 你有一个列查询返回多行(@ charge,@rate和XML类型.)我希望你发布的查询给出错误:

Only one expression can be specified
in the select list when the subquery
is not introduced with EXISTS.

但是,通过将查询移动到外部应用程序可以轻松修复此问题.要删除双重附加费元素,您可以将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>

第一个元素来自union的顶部,其中surcharge = null.

点赞