SQL Server 如何将XML列内多个节点值拼接为关联查询列
问题描述
我有如下一张表,其中包含一个XML类型的列:
| Id | Label | Details |
|---|---|---|
| 1 | Test1 | <terms><destination><email>email11@foo.com</email><email>email12@foo.com</email></destination><content>blabla</content></terms> |
| 2 | Test2 | <terms><destination><email>email21@foo.com</email><email>email22@foo.com</email></destination><content>blabla</content></terms> |
我希望编写查询语句,实现如下输出效果:
| Id | Label | Destination |
|---|---|---|
| 1 | Test1 | email11@foo.com, email12@foo.com |
| 2 | Test2 | email21@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
相关产品推荐
相关产品推荐

