5

I'm having issues querying XML data stored in a SQL Server 2012 database. The node tree I wish to query is in the following format -

<eForm>
   <page id="equalities" visited="true" complete="true">
      <Belief>
         <item selected="True" value="Christian">Christian</item>
         <item selected="False" value="Jewish">Jewish</item>
         ...
      </Belief>
   </page>
</eForm>

What I would like to do is return the value attribute of the item node where the selected attribute is equal to true. I've read several tutorials on querying XML in SQL but can't seem to get the code right.

Thanks Stu

SqlSandwiches
  • 187
  • 1
  • 9
StuartO
  • 53
  • 1
  • 1
  • 4

3 Answers3

4

DEMO

SELECT [value].query('data(eForm/page/Belief/item[@selected="True"]/@value)')
FROM test
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
1
select
    Value.value('(eForm/page/Belief/item[@selected="True"])[1]/@value', 'nvarchar(max)')    
from test

sql fiddle demo

Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
0
DECLARE @T TABLE (X XML);
INSERT @T VALUES ('<eForm>
                       <page id="equalities" visited="true" complete="true">
                          <Belief>
                             <item selected="True" value="Christian">Christian</item>
                             <item selected="False" value="Jewish">Jewish</item>
                          </Belief>
                       </page>
                    </eForm>')

SELECT  item.value('item[1]', 'NVARCHAR(50)')       
FROM    @T
        CROSS APPLY X.nodes('eForm/page/Belief') i (item)
WHERE   item.value('(item[1]/@selected)[1]', 'VARCHAR(5)') = 'true';

N.B.

I actually prefer the other approach posted by MarcinJuraszek, however there could be advantages to the below if you require further data to extract. I originally deleted the answer but there could be situations where this approach is useful so in the interest of showing all options I have undeleted.

GarethD
  • 68,045
  • 10
  • 83
  • 123