Having an issue trying to retreive the parent and children values together from the XML. The code looks as below but only able to retrieve 1 child per parent. How do I select all the children with the parent?
declare @x xml;
set @x = '
<Parent ParentID="1" ParentName="Mary">
<Child ChildID="2" ChildName="Paul" />
<Child ChildID="3" ChildName="Alan" />
<Child ChildID="4" ChildName="David" />
</Parent>
<Parent ParentID="5" ParentName="James">
<Child ChildID="6" ChildName="Amy" />
<Child ChildID="7" ChildName="Julie" />
</Parent>
';
select
tbl.col.value('@ParentID', 'int') AS ParentID,
tbl.col.value('@ParentName', 'varchar(50)') AS ParentName,
tbl.col.value('Child[1]/@ChildID[1]', 'int') AS ChildID,
tbl.col.value('Child[1]/@ChildName[1]', 'varchar(50)') AS ChildName
from @x.nodes('/Parent') as tbl(col);
I get the following results but want the parent to repeat for every child node.
ParentID ParentName ChildID ChildName
1 Mary 2 Paul
5 James 6 Amy
The problem is the Child[1] but I dont know how to get around it. I tried sql-variable but couldnt get that to work either. Ideally I want to see the following :
ParentID ParentName ChildID ChildName
1 Mary 2 Paul
1 Mary 3 Alan
1 Mary 4 David
5 James 6 Amy
5 James 7 Julie
Any help would be much appreciated. Thanks.
XML documents are formed as element trees. An XML tree starts at a root element and branches from the root to child elements. The terms parent, child, and sibling are used to describe the relationships between elements. Parents have children. Children have parents. Siblings are children on the same level (brothers and sisters).
An XML tree starts at a root element and branches from the root to child elements. The terms parent, child, and sibling are used to describe the relationships between elements. Parents have children.
The <book> elements have 4 child elements: <title>, <author>, <year>, <price>. You can assume, from this example, that the XML document contains information about books in a bookstore.
Self-Describing Syntax. XML uses a much self-describing syntax. The <book> elements have 4 child elements: <title>, <author>, <year>, <price>. You can assume, from this example, that the XML document contains information about books in a bookstore.
select
tbl.col.value('parent::*/@ParentID', 'int') AS ParentID,
tbl.col.value('parent::*/@ParentName', 'varchar(50)') AS ParentName,
tbl.col.value('@ChildID', 'int') AS ChildID,
tbl.col.value('@ChildName', 'varchar(50)') AS ChildName
from @x.nodes('/Parent/Child') as tbl(col);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With