12

此 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)' )
4

3 回答 3

19

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

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

尽管从您的“不必要的复杂”示例来看,它似乎令人担忧地简单..

于 2009-09-08T12:14:04.940 回答
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
于 2009-09-08T11:34:37.263 回答
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

于 2018-01-03T09:18:15.460 回答