Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 XPath

We're trying to filter a set of XML based on a value we provide.

We have the following XML in an XML field with our database, and if passing through the number "5052095050830", we need to find this specific node in the XML. The number we provide may exist any number of times.

Can any body provide some example SQL to assist?

Thanks

<Attributes>
  <ProductVariantAttribute ID="4387">
    <ProductVariantAttributeValue>
      <Value>5052095050830</Value>
    </ProductVariantAttributeValue>
  </ProductVariantAttribute>
  <ProductVariantAttribute ID="9999">
    <ProductVariantAttributeValue>
      <Value>5052095050830</Value>
    </ProductVariantAttributeValue>
  </ProductVariantAttribute>
  <ProductVariantAttribute ID="4388">
    <ProductVariantAttributeValue>
      <Value>104401330A</Value>
    </ProductVariantAttributeValue>
  </ProductVariantAttribute>
  <ProductVariantAttribute ID="4389">
    <ProductVariantAttributeValue>
      <Value>6905</Value>
    </ProductVariantAttributeValue>
  </ProductVariantAttribute>
  <ProductVariantAttribute ID="4390">
    <ProductVariantAttributeValue>
      <Value>6906</Value>
    </ProductVariantAttributeValue>
  </ProductVariantAttribute>
  <ProductVariantAttribute ID="4391">
    <ProductVariantAttributeValue>
      <Value>Monday, October 27, 2008</Value>
    </ProductVariantAttributeValue>
  </ProductVariantAttribute>
</Attributes>
like image 767
ajbrun Avatar asked Jun 21 '26 09:06

ajbrun


1 Answers

You can use the .exist() method - something like this:

SELECT 
(list of columns) 
FROM
dbo.YourTable
WHERE
YourXmlColumn.exist('//Value[text()="5052095050830"]') = 1

This checks against that particular value you've supplied. The more precisely you can define the XPath where that value is expected to be found, the better for your performance.

YourXmlColumn.exist('//Value[text()="5052095050830"]') = 1

is pretty bad - it looks into every single <Value> node anywhere in the XML to find that value.

Something like this:

YourXmlColumn.exist('/Attributes/ProductVariantAttribute/ProductVariantAttributeValue/Value[text()="5052095050830"]') = 1

would be much more focused and thus much better for performance - but it would only those those particular nodes defined by that very XPath statement

like image 79
marc_s Avatar answered Jun 25 '26 01:06

marc_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!