从SQL Server列获取XML节点作为逗号分隔列表

时间:2021-10-05 00:18:31

I have a data stored in a xml column and need a comma-separated list of child nodes. Using script below, I can only get "A B C". Please help me get "A,B,C" using xquery (Simple replace of space with comma does not help because we have data with spaces inside).

我有一个存储在xml列中的数据,需要以逗号分隔的子节点列表。使用下面的脚本,我只能获得“A B C”。请帮助我使用xquery获取“A,B,C”(用逗号简单替换空格没有帮助,因为我们有内部空格的数据)。

create table Temp12345 (col1 xml)
go

insert into Temp12345 (col1)
values('<fd><field i="22"><v>A</v><v>B</v><v>C</v></field></fd>')
go

select col1.value('(/fd/field[@i=22])[1] ', 'NVarchar(Max)') 
from Temp12345
go

drop table Temp12345
go

2 个解决方案

#1


8  

Try this:

SELECT
    STUFF((SELECT 
              ',' + fd.v.value('(.)[1]', 'varchar(10)')
           FROM 
              Temp12345
           CROSS APPLY
              col1.nodes('/fd/field/v') AS fd(v)
           FOR XML PATH('')
          ), 1, 1, '')

This gives me A,B,C - does it work for you, too?

这给了我A,B,C - 它也适合你吗?

#2


0  

In a full complain XQuery processor you could use just:

在一个完全抱怨的XQuery处理器中你可以使用:

(/fd/field[@i=22])[1]/string-join(*,',')

#1


8  

Try this:

SELECT
    STUFF((SELECT 
              ',' + fd.v.value('(.)[1]', 'varchar(10)')
           FROM 
              Temp12345
           CROSS APPLY
              col1.nodes('/fd/field/v') AS fd(v)
           FOR XML PATH('')
          ), 1, 1, '')

This gives me A,B,C - does it work for you, too?

这给了我A,B,C - 它也适合你吗?

#2


0  

In a full complain XQuery processor you could use just:

在一个完全抱怨的XQuery处理器中你可以使用:

(/fd/field[@i=22])[1]/string-join(*,',')