DC07
DC07

Reputation: 303

SQL Server OPENXML v XQUERY Performance

I've been testing both OpenXML and XQuery and OpenXML is out performing XQuery by a lot (I believe it should be the other way around from what I have been reading)

I prefer to use XQuery so I'm looking for some help. Any way to improve the Xquery?

I have around 10,000 of these XMLs in a table (and much larger than this example)

 <Root>
  <Data Code="123" Ref="1">
    <Node>
      <Details Date="2021-06-28" Code="ABC" />
      <Types>
        <Type Type="3" Count="29" />
        <Type Type="5" Count="0" />       
          <TypeDetails Date2="2021-06-30" />
        </Type>
      </Types>
      <Invoice Number="1234" Version="1" />
    </Node>
  </Data>
</Root>

OpenXML query:

    DECLARE name_cursor CURSOR  
FOR  
   SELECT XML   
   FROM  [dbo].[table]
OPEN name_cursor  
DECLARE @xmlVal XML  
DECLARE @idoc int  
FETCH NEXT FROM name_cursor INTO @xmlVal  
  
WHILE (@@FETCH_STATUS = 0)  
BEGIN  
   EXEC sp_xml_preparedocument @idoc OUTPUT, @xmlVal  
  
 INSERT INTO finaltable 
SELECT  Code, Ref, Date, Code, Number,Version, Type, Count,Date2
FROM OPENXML(@iDoc, 'Root/Data/Node/Types/Type')
WITH 
(
Code [varchar](50) '../../../@Code',
Ref [varchar](50) '../../../@Ref',
Date [varchar](50) '../../Details/@Date',
Code [varchar](50) '../../Details/@Code',
Number [varchar](50) '../../Invoice/@Number',
Version [varchar](50) '../../Invoice/@Version',
Type [varchar](50) '@Type',
Count [varchar](50) '@Count',
Date2 [varchar](50) 'TypeDetails/@Date2'

)

   EXEC sp_xml_removedocument @idoc  
   FETCH NEXT FROM name_cursor INTO @xmlVal  
END  
CLOSE name_cursor  
DEALLOCATE name_cursor 

XQuery (I have also tried different versions with CROSS APPLY for each node):

    INSERT INTO finaltable
select 
 c.value('(../../../@Code)[1]','nvarchar(50)') as  Code
 ,c.value('(../../../@Ref)[1]','nvarchar(50)') as  Ref
 ,c.value('(../../Details/@Date)[1]','nvarchar(50)') as  Date
 ,c.value('(../../Details/@Code)[1]','nvarchar(50)') as  Code
      ,c.value('@Type','nvarchar(50)') as  Type
      ,c.value('@Count','nvarchar(50)') as  Count
      ,c.value('(TypeDetails/@Date2)[1]','nvarchar(50)') as  Date2  
 ,c.value('(../../Invoice/@Number)[1]','nvarchar(50)') as  Number
 ,c.value('(../../Invoice/@Version)[1]','nvarchar(50)') as  Version

from [dbo].[table] 
CROSS APPLY XML.nodes('Root/Data/Node/Types/Type') as t(c)

Upvotes: 1

Views: 645

Answers (0)

Related Questions