June 16, 2016 at 12:10 pm
Hi, I really need your help with splitting an XML value into multiple rows by the top most element. Please HELP. Thank you so much!
<Parent>
<Child01>abc</Child01>
</Parent>
<Parent>
<Child02>edf</Child02>
</Parent>
<Parent>
<Child03>ghi</Child03>
</Parent>
<Parent>
<Child04>klm</Child04>
</Parent>
I have this one row in an XML colomn in my SQL table and I need to split each Parent into multiple rows. For example above, the result should come out as 4 rows as something like this:
Row 1 = <Parent><Child01>abc</Child01></Parent>
Row 2 = <Parent><Child02>edf</Child02></Parent>
Row 3 = <Parent><Child03>ghi</Child03></Parent>
Row 4 = <Parent><Child04>klm</Child04></Parent>
June 16, 2016 at 12:46 pm
Check the code and explanation for the delimited splitter in here: http://www.sqlservercentral.com/articles/Tally+Table/72993/
Be aware that it's limited in length, so you need to be sure that you're not truncating anything.
Here's an example of its usage:
CREATE TABLE #Test(
SomeXml Xml);
INSERT INTO #Test VALUES('<Parent>
<Child01>abc</Child01>
</Parent>
<Parent>
<Child02>edf</Child02>
</Parent>
<Parent>
<Child03>ghi</Child03>
</Parent>
<Parent>
<Child04>klm</Child04>
</Parent>');
SELECT s.*
FROM #Test
CROSS APPLY( SELECT STUFF(REPLACE(CAST(SomeXml AS nvarchar(4000)), N'<Parent>', NCHAR(7) + '<Parent>'), 1, 1, ''))x(DelString)
CROSS APPLY dbo.DelimitedSplitN4K( x.DelString, NCHAR(7))s;
GO
DROP TABLE #Test;
June 16, 2016 at 4:50 pm
Thank you so much. You are very good. You reminded me about this function I used before. Iteeaked it a bit to nvarchar(max) because my xml file is really huge. It takes more than an hour to run and It hasn't complete yet. Will let you know how it goes. Crossing my fingers!!
June 16, 2016 at 8:18 pm
Another way...
SELECT
ROW_NUMBER() OVER (ORDER BY x.value('.','varchar(100)')), -- only if you want a row number
x.query('.')
FROM #Test t
CROSS APPLY t.SomeXml.nodes('/Parent') a(x);
-- Itzik Ben-Gan 2001
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply