[英]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.