Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SQL to query an XML data column

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

like image 768
StuartO Avatar asked Aug 16 '13 09:08

StuartO


2 Answers

DEMO

SELECT [value].query('data(eForm/page/Belief/item[@selected="True"]/@value)')
FROM test
like image 199
MarcinJuraszek Avatar answered Oct 15 '22 04:10

MarcinJuraszek


select
    Value.value('(eForm/page/Belief/item[@selected="True"])[1]/@value', 'nvarchar(max)')    
from test

sql fiddle demo

like image 31
Roman Pekar Avatar answered Oct 15 '22 04:10

Roman Pekar