Reputation: 2504
All,
I have the below sample XML:
<Root>
<Sample1>Sample1</Sample1>
<Sample2>Sample2</Sample2>
<Run>
<Entry>
<Level1A>Test1</Level1A>
<Level1B>Test2</Level1B>
<Level1C>Test3</Level1C>
<Group>
<Level3>Test6</Level3>
<Level3>Test7</Level3>
<Level3>Test8</Level3>
<Level3>Test9</Level3>
<Level3>Test10</Level3>
<Level3>Test11</Level3>
<Level3>Test12</Level3>
<Level3>Test13</Level3>
</Group>
</Entry>
</Run>
</Root>
I would like to insert the above in a table in SQL Server 2005 database The way it should be inserted follows:
Sample1, Sample2, Test1, Test2, Test3, Test6
Sample1, Sample2, Test1, Test2, Test3, Test7
Sample1, Sample2, Test1, Test2, Test3, Test8
Sample1, Sample2, Test1, Test2, Test3, Test9
Sample1, Sample2, Test1, Test2, Test3, Test10
Sample1, Sample2, Test1, Test2, Test3, Test11
Sample1, Sample2, Test1, Test2, Test3, Test12
Sample1, Sample2, Test1, Test2, Test3, Test13
As you can see the rows is as many as the elements of Level3
Based on this fact, I have a stored procedure
INSERT INTO @TESTTEMP
SELECT
ent.query('../../../../Sample1').value('.','VARCHAR(20)') As A
ent.query('../../../../Sample2').value('.','VARCHAR(20)') As B
ent.query('../../Level1A').value('.','VARCHAR(20)') As D,
ent.query('../../Level1B').value('.','VARCHAR(20)') As E,
ent.query('../../Level1C').value('.','VARCHAR(20)') As F,
ent.query('Level3').value('.','VARCHAR(20)') As G,
FROM @xmlMessage.nodes('//Root/Run/Entry/Group/Level3') Col(ent)
The code above works perfectly fine but very very slow. I know the issue is for every row I backtrack on the tree 2 or even 4 levels. How can I speed this thing up ?
Many Thanks, MK
Upvotes: 2
Views: 427
Reputation: 138960
I had to fix your XML a bit but here is what I think you want.
declare @xmlMessage xml =
'<Root>
<Sample1>Sample1</Sample1>
<Sample2>Sample2</Sample2>
<Run>
<Entry>
<Level1A>Test1</Level1A>
<Level1B>Test2</Level1B>
<Level1C>Test3</Level1C>
<Group>
<Level3>Test6</Level3>
<Level3>Test7</Level3>
<Level3>Test8</Level3>
<Level3>Test9</Level3>
<Level3>Test10</Level3>
<Level3>Test11</Level3>
<Level3>Test12</Level3>
<Level3>Test13</Level3>
</Group>
</Entry>
</Run>
</Root>'
SELECT T1.Col.value('Sample1[1]', 'varchar(20)') as A,
T1.Col.value('Sample2[1]', 'varchar(20)') as B,
T2.Col.value('Level1A[1]', 'varchar(20)') as D,
T2.Col.value('Level1B[1]', 'varchar(20)') as E,
T2.Col.value('Level1C[1]', 'varchar(20)') as F,
T3.Col.value('.', 'varchar(20)') as G
FROM @xmlMessage.nodes('/Root') as T1(Col)
cross apply T1.Col.nodes('Run/Entry') as T2(Col)
cross apply T2.Col.nodes('Group/Level3') as T3(Col)
You need to test it yourself for speed but I think this will be a bit faster. According to the query plan your take 99% and this takes 1% of the time.
Upvotes: 1