小编典典

如何查询SQL Server XML列并返回特定节点的所有值?

sql

我在SQL Server的XML列中有以下XML。

  <qualifiers>
    <qualifier>
      <key>111</key>
      <message>a match was not found</message>
    </qualifier>
    <qualifier>
      <key>222</key>
      <message>a match was found</message>
    </qualifier>
    <qualifier>
      <key>333</key>
      <message>error</message>
    </qualifier>
  </qualifiers>

如何编写TSQL以逗号分隔的字符串返回限定符/限定符/消息中的所有值?我的目标是让查询在每一行的单个列中返回XML中的值。

结果应如下所示:

"a match was not found, a match was found, error"

阅读 235

收藏
2021-05-30

共1个答案

小编典典

SQLFiddle的相同之处:建议按照@xQbert的解决方案

create table Temp (col1 xml)
go

insert into Temp (col1)
values('<qualifiers>
    <qualifier>
      <key>111</key>
      <message>a match was not found</message>
    </qualifier>
    <qualifier>
      <key>222</key>
      <message>a match was found</message>
    </qualifier>
    <qualifier>
      <key>333</key>
      <message>error</message>
    </qualifier>
  </qualifiers>')
go

SELECT
    STUFF((SELECT 
              ',' + fd.v.value('(.)[1]', 'varchar(50)')
           FROM 
              Temp
           CROSS APPLY
              col1.nodes('/qualifiers/qualifier/message') AS fd(v)
           FOR XML PATH('')
          ), 1, 1, '')
2021-05-30