Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select from parent-children xml content

I have been looking for solution for selecting parent-child relation from table [Group] which contains a xml column.

[Group] table has the following structure:

  • ID – int
  • Content – xml

There is xml data – parent-child relation in column Content

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<root>
    <person name="John">
        <device name="notebook" />
        <device name="xbox" />   
    </person>
    <person name="Jane">
        <device name="TV" />
    </person>
    <person name="Mark">
    </person>
</root>

I would like to select data in the following format:

Group Id PersonName DeviceName
1 John notebook
1 John xbox
1 Jane TV

Because Mark has no device assigned, there is no row for Mark in result.
Is it possible to achieve this result in a SELECT query?

>Solution :

As I mentioned, you can use XQuery for this. As you don’t want any rows for Mark, I go straight to the device node, in the nodes method, as this means that no rows for Mark will be found. Then you can go back up one level to get the person’s name:

SELECT V.ID AS GroupID,
       p.d.value('../@name','nvarchar(50)') AS PersonName,
       p.d.value('@name','nvarchar(50)') AS DeviceName
FROM(VALUES(1,CONVERT(xml,'<root>
    <person name="John">
        <device name="notebook" />
        <device name="xbox" />   
    </person>
    <person name="Jane">
        <device name="TV" />
    </person>
    <person name="Mark">
    </person>
</root>')))V(ID, Content)
     CROSS APPLY V.Content.nodes('root/person/device') p(d);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading