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

How can I query a SQL Server XML column and return all values for a specific node?(如何查询 SQL Server XML 列并返回特定节点的所有值?)
本文介绍了如何查询 SQL Server XML 列并返回特定节点的所有值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following XML in a XML column in SQL Server.

  <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 中的值.

How can I write TSQL to return all the values in qualifiers/qualifier/message in a comma delimited string? My goal is to have the query return the values from the XML in a single column for each row.

结果应该是这样的:

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

推荐答案

SQLFiddle for相同:根据@xQbert 建议的解决方案

SQLFiddle for the same: Solution as per @xQbert suggested

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, '')

这篇关于如何查询 SQL Server XML 列并返回特定节点的所有值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)