1

I have a XML as below in one of the table column of type xml

<fields>
  <field>
    <name>SourceFileName</name>
    <value>ABCD</value>
  </field>
  <field>
    <name>Template</name>
    <value>XYZ</value>
  </field>
</fields>

I need to query the XML to get the value for a specific text in field/name node

i used the below SQL but it doesn't return any data for the second one

SELECT *
FROM   xmltable
WHERE  XMLText.value('(/fields/field/name)**[1]**' ,'varchar(max)') LIKE 
       'Template'

SELECT *
FROM   xmltable
WHERE  XMLText.value('(/fields/field/name)**[1]**' ,'varchar(max)') LIKE 
       'SourceFileName'

whereas the below returns data

SELECT *
FROM   xmltable
WHERE  XMLText.value('(/fields/field/name)**[2]**' ,'varchar(max)') LIKE 
       'Template'

Can somebody help, how do i write a generic query to return data based on the name passed?

1
  • How does this work for Update - Update @T Set XMLText.modify('replace value of (value/text())[1] with sql:variable("@NewVal")') FROM @T CROSS APPLY XMLText.nodes('/fields/field') AS XT(XC) where XC.value('(name)[1]', 'varchar(50)') like 'Template' Commented Nov 24, 2015 at 11:35

1 Answer 1

1

If you want to handle multiple XML elements, you need to use the .nodes() XQuery function.

Try something like this:

SELECT
    Name = XC.value('(name)[1]', 'varchar(50)'),
    [Value] = XC.value('(value)[1]', 'varchar(25)')
FROM
    dbo.XmlTable
CROSS APPLY
    XmlText.nodes('/fields/field') AS XT(XC)

The .nodes() call will create a "pseudo" table XT with a single column XC that contains the XML fragment that is matched by that XPath expression - in your case, you get two rows, each representing one of the <field> elements.

You can now "reach into" those XML fragments and extract the data you need using the .value() calls - and you get the name and value for both <field> elements this way:

enter image description here

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

2 Comments

Thank you marc. It worked like a charm. Kudos for your quick response.
Another quick question. How does this work for Update - Update @T Set XMLText.modify('replace value of (value/text())[1] with sql:variable("@NewVal")') FROM @T CROSS APPLY XMLText.nodes('/fields/field') AS XT(XC) where XC.value('(name)[1]', 'varchar(50)') like 'Template'

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.