0

I have a XML column in a database with the following

<SelectedValues haveDefaultsBeenSet="true">
  <SelectedValue>
    <Name>Item Condition</Name>
    <Value>New</Value>
    <ValueID>1000</ValueID>
  </SelectedValue>
  <SelectedValue>
    <Name>Brand</Name>
    <Value>Sony</Value>
  </SelectedValue>
  <SelectedValue>
    <Name>MPN</Name>
    <Value>8</Value>
  </SelectedValue>
  <SelectedValue>
    <Name>Model</Name>
    <Value>DVD</Value>
  </SelectedValue>
  <SelectedValue>
    <Name>MFR</Name>
    <Value>Sony</Value>
  </SelectedValue>
  <SelectedValue>
    <Name>PackQuantity</Name>
    <Value>3</Value>
  </SelectedValue>
</SelectedValues>

I'm trying to return the Value when the name matches MFR. So when I'm searching for MFR I'M looking for result Sony

I have tried this

SELECT Itemspecifics.value('(/SelectedValues/SelectedValue/Value)[1]', 'varchar(max)') as MFR
FROM [SixBit_BT].[dbo].[ItemsEbay]
Where itemspecifics.exist('//.[text()="MFR"]') = 1

Which does work to show only results that have MFR in the XML column, but it gives me the first value in this case 'New'. If i change the [1] to [5]. I do get the correct result for this example but it is not always in that position.

2 Answers 2

1

My xpath is a little rusty but I think you want something like this:

'(/SelectedValues/SelectedValue[Name="MFR"]/Value)[1]'

Or maybe just this since it should give you a single item

'/SelectedValues/SelectedValue[Name="MFR"]/Value'

Here is a similar xpath example for little sanity check, since I'm not in a position to test this myself at the moment: How to get value through xpath for repeating tags,it's like key value pair

0
0

Your code just select the first Value node, not the first one that matches "MFR". Use this instead:

SELECT Itemspecifics.query('//SelectedValue[Name = "MFR"]/Value').value('.[1]','varchar(max)')
FROM [SixBit_BT].[dbo].[ItemsEbay]
Where itemspecifics.exist('//.[text()="MFR"]') = 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.