Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where clause on a SQL Server XML column filtering on attribute AND value

I have a 'Metadata' field in table 'Document' that has the following data:

<properties>
  <property name="someProp">xyz</property>
  <property name="reportId">55</property>
  <property name="someOtherProp">abc</property>
</properties>'

How can I write a query that returns records where a property element exists with a name of "reportId" and that "reportId" property element has a value of 55? Sometimes the "reportId" property node is the only one that exists, sometimes not, and it's not always in the above order so I can't query on absolute positions. Any ideas?

like image 342
user1380769 Avatar asked Dec 20 '12 03:12

user1380769


2 Answers

There is no need to extract the value. Use exist() Method (xml Data Type) instead.

select *
from Document
where Metadata.exist('/properties/property[@name="reportId" and . = 55]') = 1
like image 142
Mikael Eriksson Avatar answered Sep 18 '22 21:09

Mikael Eriksson


Nevermind, got it. For reference:

select * from Document
where Metadata.value('(/properties/property[@name="reportId"])[1]', 'int') = 55
like image 35
user1380769 Avatar answered Sep 18 '22 21:09

user1380769