I have a DB table with an XML data type column. The column contains the following values:
<NameValuePairCollection> <NameValuePair Name="Foo" Value="One" /> <NameValuePair Name="Bar" Value="Two" /> <NameValuePair Name="Baz" Value="Three" /> </NameValuePairCollection>
I am trying to query for all rows where the column of the XML data type is set to "One" for "Foo" . I had a problem creating the appropriate XQuery to filter the results.
I found a couple of related SO questions that helped me in my attempt, but I still can't get it to work.
How can I query the value in SQL Server XML column
Use LIKE record in SQL Server XML format
Here is the SQL that I have so far:
select * from MyTable where [XmlDataColumn].value('((/NameValuePairCollection/NameValuePair)[@Name="Foo"])[@Value]', 'varchar(max)') = 'One' order by ID desc
Here is the error that I am getting right now:
XQuery [MyTable.XmlDataColumn.value()]: Cannot atomize/apply data() on expression that contains type 'NameValuePair' within inferred type 'element(NameValuePair,#anonymous) *'
UPDATE (in response to @ LeoWörteler's suggestion)
Based on your answer, I changed my SQL to this:
select * from MyTable with(nolock) where [XmlDataColumn].value('/NameValuePairCollection/NameValuePair[@Name="Subject"]/@Value', 'varchar(max)') = 'One' order by ID desc
This still does not work. I get the following error:
XQuery [MyTable.XmlDataColumn.value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xs:string *'