You need to enable JavaScript to run this app. SQL Server 如何将XML列内多个节点值拼接为关联查询列
优惠活动
大模型
产品
解决方案
定价
更多

SQL Server 如何将XML列内多个节点值拼接为关联查询列

问题描述

我有如下一张表,其中包含一个XML类型的列:

IdLabelDetails
1Test1<terms><destination><email>email11@foo.com</email><email>email12@foo.com</email></destination><content>blabla</content></terms>
2Test2<terms><destination><email>email21@foo.com</email><email>email22@foo.com</email></destination><content>blabla</content></terms>

我希望编写查询语句,实现如下输出效果:

IdLabelDestination
1Test1email11@foo.com, email12@foo.com
2Test2email21@foo.com, email22@foo.com

请问该如何实现将XML中email节点的取值拼接为独立列,并与关联的Id、Label字段一同查询输出?


实现代码

SQL Server 2017+ 版本

假设表名为 TestTable,执行以下查询即可得到目标结果:

SELECT 
    t.Id,
    t.Label,
    STRING_AGG(d.Email, ', ') AS Destination
FROM TestTable t
CROSS APPLY (
    SELECT Details.value('(./text())[1]', 'VARCHAR(200)') AS Email
    FROM t.Details.nodes('/terms/destination/email') AS T(Details)
) d
GROUP BY t.Id, t.Label;

低版本SQL Server(2016及更早,无STRING_AGG支持)

SELECT 
    t.Id,
    t.Label,
    STUFF(
        (SELECT ', ' + inner.Email
         FROM (
             SELECT Details.value('(./text())[1]', 'VARCHAR(200)') AS Email
             FROM t.Details.nodes('/terms/destination/email') AS T(Details)
         ) inner
         FOR XML PATH('')),
        1, 2, ''
    ) AS Destination
FROM TestTable t;

PostgreSQL 实现

SELECT 
    Id,
    Label,
    STRING_AGG(xml_text::TEXT, ', ') AS Destination
FROM TestTable
CROSS JOIN LATERAL UNNEST(xpath('/terms/destination/email/text()', Details)) AS x(xml_text)
GROUP BY Id, Label;

内容的提问来源于stack exchange,提问作者lai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.03 14:54:11