【问题标题】:Parsing OpenXML with multiple elements of the same name使用多个同名元素解析 OpenXML
【发布时间】:2011-11-04 16:58:58
【问题描述】:

我有一个这样的数据结构:

<rootnode>
  <group>
    <id>1</id>
     <anothernode>first string</anothernode>
     <anothernode>second string</anothernode>
  </group>
 <group>
   <id>2</id>
     <anothernode>third string</anothernode>
     <anothernode>fourth string</anothernode>
  </group>
</rootnode>

还有如下代码:

EXEC sp_xml_preparedocument @index OUTPUT, @XMLdoc

SELECT *
FROM OPENXML (@index, 'rootnode/group')
WITH 
(
  id int 'id',
  anothernode varchar(30) 'anothernode'
)

这给了我结果

id | anothernode
————————————————
1  | first string
2  | third string

我怎样才能让它显示这个结果而不是显示所有四个字符串?

id | anothernode
————————————————
1  | first string
1  | second string
2  | third string
2  | fourth string

【问题讨论】:

    标签: sql sql-server sql-server-2008 openxml sql-server-openxml


    【解决方案1】:
    SELECT *
    FROM OPENXML (@index, 'rootnode/group/anothernode')
    WITH 
    (
      id int '../id',
      anothernode varchar(30) '.'
    )
    

    或者您可以像这样使用 XML 数据类型:

    SELECT G.N.value('(id/text())[1]', 'int') AS id,
           A.N.value('text()[1]', 'varchar(30)') AS anothernode
    FROM @XMLDoc.nodes('rootnode/group') AS G(N)
      CROSS APPLY G.N.nodes('anothernode') AS A(N)
    

    【讨论】:

    • 非常感谢!你会推荐其中一个吗?
    • 嗯,这似乎将一行输出为“1 | 第一个字符串第二个字符串”有什么方法可以在两个具有相同 ID 的单独行上获得“第一个字符串”和“第二个字符串”?
    • @billynomates,我建议您使用第二个版本(XML 数据类型)。
    • @billynomates 该查询对我来说很好。在这里测试:data.stackexchange.com/stackoverflow/q/116679
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多