December 29, 2011 at 2:55 am
Hi All,
Iam having the xml with the data as shown below,
declare @x xml
set @x = '<SinterklaasWishlists>
<child>
<name>Tim</name>
<wishlist>
<article>
<artno>21491269</artno>
<description>Crane</description>
<price>12.50</price>
</article>
<article>
<artno>21499517</artno>
<description>Keyboard</description>
<price>10</price>
</article>
<article>
<artno>21521591</artno>
<description>Crime Investigation Game</description>
<price>9.95</price>
</article>
</wishlist>
</child>
<child>
<name>Tim2</name>
<wishlist>
<article>
<artno>3145678</artno>
<description>Mouse</description>
<price>12.50</price>
</article>
</wishlist>
</child>
</SinterklaasWishlists>'
I want to extract the elements of xml using sql query and insert the data into the table as shown below:
CHILDNAME ARTICLE_NUMBER DESCRIPTION PRICE
--------------- -------------------- ----------------------------------- -----------
Tim1 21491269 Crane 12.50
Tim1 21499517 Keyboard 10
Tim1 21521591 Crime Investigation Game 9.95
Tim2 3145678 Mouse 12.50
Kindly help me on the same
January 5, 2012 at 7:14 am
This is one way to shred the example xml into the format ready for you to insert into a table:
select c.value('../../name[1]', 'varchar(100)'),
c.value('artno[1]', 'varchar(100)'),
c.value('description[1]', 'varchar(100)'),
c.value('price[1]', 'money')
from @x.nodes('//article') t(c)
Hope this gets you onto the right track.
January 5, 2012 at 9:33 am
thanks a lot dude 🙂 it worked like a charm 2 me 🙂
January 5, 2012 at 9:36 am
No Problem. thanks for the feedback.
January 5, 2012 at 1:43 pm
I'd rather use the CROSS APPLY approach to avoid "climbing up" two levels for each article node to get the name element. Performance impact can be significant depending on the xml size and node structure.
SELECT
c.value('name[1]', 'varchar(100)'),
v.value('artno[1]', 'varchar(100)'),
v.value('description[1]', 'varchar(100)'),
v.value('price[1]', 'money')
FROM @x.nodes('SinterklaasWishlists/child') t(c)
CROSS APPLY T.c.nodes('wishlist/article')u(v)
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply