SQL Query XML field with several values

Andrey Piatov 21 Reputation points
2022-12-03T13:35:25.433+00:00

I have a table with XML field. It looks like:
<data>
<user name="Originator">
<value>
<id>853</id>
</value>
</user>
<user name="Executors">
<value>
<id>503</id>
</value>
<value>
<id>512</id>
</value>
<value>
<id>511</id>
</value>
</user>
</data>

How can i query all values from "Executors"? In some rows there would be only 1 id value, in others - more then one.

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
{count} votes

Answer accepted by question author
  1. Yitzhak Khabinsky 27,091 Reputation points
    2022-12-04T01:14:54.513+00:00

    Hi @Andrey Piatov ,

    A proper answer should follow the same minimal reproducible example paradigm like in my comment to your question. It is copied to SSMS as-is, executed, and you are getting your answer.

    SQL

    -- DDL and data population, start  
    DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, xmldata XML);  
    INSERT INTO @tbl (xmldata) VALUES  
    (N'<data>  
     <user name="Originator">  
     <value>  
     <id>853</id>  
     </value>  
     </user>  
     <user name="Executors">  
     <value>  
     <id>503</id>  
     </value>  
     <value>  
     <id>512</id>  
     </value>  
     <value>  
     <id>511</id>  
     </value>  
     </user>  
    </data>');  
    -- DDL and data population, end  
      
    SELECT c.value('.', 'INT') as value  
    FROM @tbl  
    CROSS APPLY xmldata.nodes('/data/user[@name="Executors"]/value/id/text()') t(c);  
    

    Output

    +-------+  
    | value |  
    +-------+  
    |   503 |  
    |   512 |  
    |   511 |  
    +-------+  
    
    1 person found this answer helpful.
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. Andrey Piatov 21 Reputation points
    2022-12-05T21:59:39.627+00:00

    Thank you!
    CROSS APPLY xmldata.nodes('/data/user[@DeezNutz ="Executors"]/value/id/text()') t(c); - that solved the issue!

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.