1

I have a table with an XML column (xmlCol) and I am trying to query a value from it.

Here's the xml.

<criteria>
  <factor name="Rivers" title="Rivers">
    <value dataType="Int32" value="1743" description="Wilson0" />
  </factor>
  <factor name="OptionalAffProperties" title="Include properties">
    <value dataType="String" value="FishingModel" description="Fishing Model" />
  </factor>
</criteria>

Here is a select to get the column. select xmlCol from MyTable

I am trying to return the value 1743 to a column called RiverID.

Mike

2 Answers 2

2

This should work:

SELECT
    xmlCol.value('(//factor[@name="Rivers"]/value/@value)[1]', 'int') As RiverID
FROM
    MyTable

value() Method (xml Data Type) - SQL Server | Microsoft Docs
XQuery Language Reference (SQL Server) - SQL Server | Microsoft Docs

Sign up to request clarification or add additional context in comments.

2 Comments

@Austin Good spot! Fixed.
/criteria/factor will be faster than //factor
1

To get the attribute value, you can query it like so:

select xmlCol.value('(/criteria/factor/value/@value)[1]', 'int') RiverID
from MyTable

You provide the xml path to the record you are looking for: (/criteria/factor/value

And then the attribute you need: /@value)[1].

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.