简体   繁体   English

如何从 T-SQL 中的 XML 列中获取以逗号分隔的字符串列表?

[英]How do I get a comma-delimited list of strings from an XML column in T-SQL?

Suppose there is a table (SQL Server 2019) with two columns.假设有一个包含两列的表 (SQL Server 2019)。 Both are nvarchar but the ResultDoc column happens to store xml.两者都是 nvarchar 但ResultDoc列恰好存储 xml。 Example data:示例数据:

Name姓名 ResultDoc结果文档
Sam山姆 <doc><results><result>a</result><result>b</result><result>x</result></results></doc>
Jan <doc><results><result>c</result><result type="pending">z</result><result>m</result><result>k</result></results></doc>

I want to be able to query this table, filtering on the xml, and get a result like this:我希望能够查询此表,过滤 xml,并获得如下结果:

Name姓名 Results结果
Sam山姆 a, b, x一,乙,X
Jan c, m, k c, 米, k

I've seen examples that do this for a single document, but I haven't been able to work a solution like that into a query that does this for several rows.我已经看到对单个文档执行此操作的示例,但是我无法将这样的解决方案应用于对多行执行此操作的查询。

Updated ... moved the aggregate into the OUTER APPLY更新...将聚合移到 OUTER APPLY

Since you are on 2019, you can use string_agg()由于您是 2019 年,您可以使用string_agg()

Example or dbFiddle示例或dbFiddle

Select A.Name
      ,C.Results
 From  YourTable A
 Outer Apply ( values (try_convert(xml,[ResultDoc]) ) )B(xmlData)
 Outer Apply (
                Select Results = string_Agg(xn.value('./text()[1]', 'nvarchar(150)'),',')
                 From xmlData.nodes('doc/results/result') C(xn)
                 Where coalesce(xn.value('@type[1]', 'nvarchar(150)'),'') not in ('pending')
              ) C

Results结果

Name    Results
Jan     c,m,k
Sam     a,b,x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 T-SQL 中获取不同的逗号分隔字符串 - Getting a distinct comma-delimited string in T-SQL 计算以逗号分隔的 SQL 列中的项目 - Count items in comma-delimited SQL column 如何将多行组合到SQL Server 2005中以逗号分隔的列表中? - How can I combine multiple rows into a comma-delimited list in SQL Server 2005? 为逗号分隔的整数列表声明T-Sql参数 - declaring T-Sql parameter for comma delimited list of integers 用逗号分隔的列表,在Oracle SQL的最后一个元素之前串联“和” - Comma-Delimited List with “and” concatenated before Last Element in Oracle SQL 如何选择出现3次的记录并将多行合并到sql server 2005中的逗号分隔列表中 - how to select records that occurs 3 times and combine multiple rows into a comma-delimited list in sql server 2005 T-SQL逗号分隔值从结果集到子查询中的in子句 - T-SQL Comma delimited value from resultset to in clause in Subquery 如何在SQL Oracle中将行列转换为以逗号分隔的字符串 - How to convert row columns to comma-delimited string in sql oracle 如何通过“ IF”条件T-SQL检查以逗号分隔的整数值? - How to check a comma delimited integer values by “IF” condition T-SQL? 如何将NVARCHAR逗号分隔列表转换为INT? - How to convert NVARCHAR comma-delimited list to INT?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM