在SQL Server中使用value()从xml列获取多个记录

时间:2009-09-08 10:40:17

标签: sql-server-2005 xquery

此SQL仅返回第一个Activity元素。我如何选择它们?如果我删除查询中的[1],我会收到“value()需要单例”的错误。

 DECLARE @myDoc xml
    SET @myDoc = 
    '<Root>
        <Activities>
            <Activity>This is activity one</Activity>
            <Activity>This is activity two</Activity>
            <Activity>This is activity three</Activity>
        </Activities>
    </Root>'

    SELECT @myDoc.value('(/Root/Activities/Activity)[1]', 'varchar(100)' )

3 个答案:

答案 0 :(得分:16)

感谢Ed,但我找到了一个更简单的版本:

SELECT T.C.value('.', 'varchar(100)') as activity
FROM @myDoc.nodes('(/Root/Activities/Activity)') as T(C)

虽然从你的“不必要的复杂”例子来看,这似乎很简单......

答案 1 :(得分:2)

这有效,但似乎不必要地复杂。可能有一种更简单的方法。

 DECLARE @myDoc xml
    SET @myDoc = 
    '<Root>
        <Activities>
            <Activity>This is activity one</Activity>
            <Activity>This is activity two</Activity>
            <Activity>This is activity three</Activity>
        </Activities>
    </Root>'

SELECT activity.VALUE('(//Activity)[1]','varchar(100)') AS activity
FROM (
        SELECT NewTable.activity.query('.') AS activity
        FROM (SELECT 1 AS col1) AS t
        CROSS APPLY @myDoc.nodes('(/Root/Activities/Activity)') AS NewTable(activity)
     ) AS x

答案 2 :(得分:-1)

这是另一种情况和解决方案:我正在搜索这种情况,其中有两个元素可以使用一个查询进行选择。

CREATE TABLE #Table1 (ID INT IDENTITY(1,1),XMLDoc XML)

INSERT INTO #Table1 VALUES ('
 <bookstore>
 <name>Bookstore1</name>
 <location>Location1</location>
 <book>
     <title>Titile1</title>
     <price>40</price>
    </book>
 </bookstore>')

 INSERT INTO #Table1 VALUES ('
 <bookstore>
  <name>Bookstore2</name>
 <location>Location2</location>
 <book>
     <title>Titile2</title>
     <price>50</price>
 </book>
</bookstore>')


SELECT ID,
T.c.value('title[1]','varchar(50)') AS 'BookTitile',
T.c.value('price[1]','decimal(18,2)') AS 'Price'
FROM #Table1
CROSS APPLY #Table1.XMLDoc.nodes('/bookstore/book') T(c)

DROP TABLE #Table1

您可以根据需要修改此项以包含XMLNamespaces。 解决方案最初位于:https://social.msdn.microsoft.com/Forums/sqlserver/en-US/35e75e32-9ffb-4a30-8637-2cc928554763/selecting-multiple-values-from-multiple-rows-of-xml?forum=sqlxml