对于SQL Server中的XML - 添加Child元素

时间:2017-07-17 17:24:01

标签: sql xml for-xml

我有以下查询

Documentation

返回此XML文件格式

enter image description here

我如何以这种格式获得它?

enter image description here

请帮助, 源代码

SELECT top 1

    (SELECT top 1
    count(*)AS 'number-of-accounts', 
    sum(br.cnsmr_accnt_bckt_crrnt_bal_amnt) AS 'total-value-of-account-payment',
    '' AS 'date-of-turnover',
    '' AS 'is-conversion-job'
    FROM
    cnsmr as c
    inner join cnsmr_accnt as ca ON c.cnsmr_id = ca.cnsmr_id
    inner join cnsmr_accnt_bckt_bal_rprtng as br on ca.cnsmr_accnt_id = br.cnsmr_accnt_id
     FOR XML PATH('payment-import-header'), TYPE),

    (SELECT  top 1
    br.cnsmr_accnt_bckt_crrnt_bal_amnt AS 'payment-amount',
    '' AS 'bucket-transaction-type',
    '' AS 'tendered-date',
    '' AS 'entered-date',
    '' AS 'payment-location-code',
    '' AS 'payment-memo-code',
    '' AS 'payment-comments',
    '' AS 'external-reference-identifier'

    FROM
    cnsmr as c
    inner join cnsmr_accnt as ca ON c.cnsmr_id = ca.cnsmr_id
    inner join cnsmr_accnt_bckt_bal_rprtng as br on ca.cnsmr_accnt_id = br.cnsmr_accnt_id

    FOR XML PATH('consumer-payment'), ROOT('consumer-payment-import'),TYPE)

FOR XML RAW (''), ROOT ('consumer-payment-import-job'), ELEMENTS XSINIL;

1 个答案:

答案 0 :(得分:3)

请使用实际的RDBMS(产品和版本)进行标记。语法和图片指向SQL-Server ...

请阅读How to ask a good SQL questionHow to create a MCVE

没有测试数据我无法测试,但以下内容应该有帮助...

SELECT top 1

    (SELECT top 1
    count(*)AS 'number-of-accounts', 
    sum(br.cnsmr_accnt_bckt_crrnt_bal_amnt) AS 'total-value-of-account-payment',
    '' AS 'date-of-turnover',
    '' AS 'is-conversion-job'
    FROM
    cnsmr as c
    inner join cnsmr_accnt as ca ON c.cnsmr_id = ca.cnsmr_id
    inner join cnsmr_accnt_bckt_bal_rprtng as br on ca.cnsmr_accnt_id = br.cnsmr_accnt_id
     FOR XML PATH('payment-import-header'), TYPE),

    (SELECT  top 1
    br.cnsmr_accnt_bckt_crrnt_bal_amnt AS 'payment-amount',
    '' AS 'bucket-transaction-type',
    '' AS 'tendered-date',
    '' AS 'entered-date',
    '' AS 'payment-location-code',
    '' AS 'payment-memo-code',
    '' AS 'payment-comments',
    '' AS 'external-reference-identifier'
    ,(
        SELECT 'SomeValue' AS Something
        FOR XML PATH('consumer-identifier'),TYPE
     )
    FROM
    cnsmr as c
    inner join cnsmr_accnt as ca ON c.cnsmr_id = ca.cnsmr_id
    inner join cnsmr_accnt_bckt_bal_rprtng as br on ca.cnsmr_accnt_id = br.cnsmr_accnt_id

    FOR XML PATH('consumer-payment'), ROOT('consumer-payment-import'),TYPE) AS [consumer-payment-imports]

FOR XML RAW (''), ROOT ('consumer-payment-import-job'), ELEMENTS XSINIL;

AS [consumer-payment-imports]将整个内部节点包装在另一个节点内。

第二个添加是另一个子选择,将您的客户参考添加到内部子选择中。如果这不是1:n,则使用

就足够了
'SomeValue' AS [consumer-identifier/Something]

这将在嵌套元素中添加值SomeValue ...