简体   繁体   English

如何在sql server 2008中选择这个xml

[英]how to select this xml in sql server 2008

I need to select all guid node in the xml. 我需要选择xml中的所有guid节点。 but the code below only select the first one of them. 但下面的代码只选择其中的第一个。 how to do it? 怎么做?

DECLARE @doc XML

SET @doc = 
    '<ArrayOfGuid xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <guid>96eecbe2-d645-465d-8232-c7f21e3c6bf8</guid>
      <guid>38985702-0c0b-4e9c-bccb-af84ba4dd7ff</guid>
      <guid>67852205-092e-4db8-b31e-6f5d457db294</guid>
      <guid>92cf9106-445f-4b01-8259-613596b8a2a7</guid>
    </ArrayOfGuid>'

DECLARE @docHandle INT

EXEC sp_xml_preparedocument @docHandle OUTPUT,
     @doc

SELECT [guid]
FROM   OPENXML(@docHandle, '/ArrayOfGuid', 2)
       WITH
       ([guid] UNIQUEIDENTIFIER)

the result is just one row: 96EECBE2-D645-465D-8232-C7F21E3C6BF8 结果只有一行:96EECBE2-D645-465D-8232-C7F21E3C6BF8

I need all 4 rows. 我需要所有4行。

There are probably better ways to do this, but here's one of them: 可能有更好的方法来做到这一点,但这里有一个:

SELECT text as guid
FROM   OPENXML(@docHandle, '//ArrayOfGuid/guid/text()', 2)

You can also use this approach using the native XQuery capabilities in SQL Server 2005 and newer: 您还可以使用SQL Server 2005及更高版本中的本机XQuery功能来使用此方法:

SELECT
    Guids.value('(.)[1]', 'uniqueidentifier')
FROM 
    @doc.nodes('/ArrayOfGuid/guid') AS XTbl(Guids)

I always prefer this method over the older OPENQUERY approach 我总是喜欢这种方法而不是旧的OPENQUERY方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM