Getting multiple records from xml column with value() in SQL Server

前端 未结 3 1845
自闭症患者
自闭症患者 2020-12-10 06:47

This SQL only returns the first Activity element. How do I select them all? If I remove the [1] in the query I get an error that \"value() requires a singleton\".

3条回答
  •  不思量自难忘°
    2020-12-10 07:09

    Here is another situation and solution: I was searching for this situation where there are two elements to be selected using one query.

    CREATE TABLE #Table1 (ID INT IDENTITY(1,1),XMLDoc XML)
    
    INSERT INTO #Table1 VALUES ('
     
     Bookstore1
     Location1
     
         Titile1
         40
        
     ')
    
     INSERT INTO #Table1 VALUES ('
     
      Bookstore2
     Location2
     
         Titile2
         50
     
    ')
    
    
    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
    

    You can modify this as required to include XMLNamespaces. Solution originally found at :https://social.msdn.microsoft.com/Forums/sqlserver/en-US/35e75e32-9ffb-4a30-8637-2cc928554763/selecting-multiple-values-from-multiple-rows-of-xml?forum=sqlxml

提交回复
热议问题