【问题标题】:Select from list of xml elements with SQL Server使用 SQL Server 从 xml 元素列表中选择
【发布时间】:2015-01-29 19:46:04
【问题描述】:

假设我有这个 xml -

   <book>
      <author>Gambardella, Matthew</author>
      <title>XML Developers Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications 
      with XML.</description>
   </book>
   <book>
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, 
      an evil sorceress, and her own childhood to become queen 
      of the world.</description>
   </book>
   <book>
      <author>Corets, Eva</author>
      <title>Maeve Ascendant</title>
      <genre>Fantasy</genre>
      <price>5.95</price>
      <publish_date>2000-11-17</publish_date>
      <description>After the collapse of a nanotechnology 
      society in England, the young survivors lay the 
      foundation for a new society.</description>
   </book>

我需要一个 T-SQL 查询来从该列表中一次选择一本书,因为我需要在将其插入表之前对其进行某种处理。

假设我想选择此列表中的第二个元素并将其显示为表格。

我该怎么做?

【问题讨论】:

    标签: sql sql-server xml xquery


    【解决方案1】:

    就我个人而言,我会先将整个 XML 文档分解成一个表,如果我真的无法对它们进行基于集合的操作,请使用行号和循环或游标之类的东西遍历表。

    如果您只是明确地想要访问 xml 文档的第 n 个成员,您可以在编写 xpath 表达式时这样做。不过,我不确定您如何知道需要迭代多少个元素。下面是一个抓取第二本书节点的例子:

    --Assumes you've assigned the XML document you provided to an XML variable called @xml
    select t.c.value('author[1]', 'varchar(50)')
    from @xml.nodes('/book[2]') as t(c)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      相关资源
      最近更新 更多