我正在努力解决查询性能问题。我将“平面”XML存储为表格中的XML。我正在尝试将该XML的所有元素和属性提取到某个平面表中。问题是我要解析大约200列/属性。 这就是它的样子:
SELECT
x.i.value('./@Id', 'nvarchar(max)') as [Id],
x.i.value('(./Elem1/text())[1]', 'nvarchar(max)') as [Elem1],
x.i.value('(./Elem2/text())[1]', 'nvarchar(max)') as [Elem2],
x.i.value('./@Attr1', 'nvarchar(max)') as [Attr1],
x.i.value('./@Attr2', 'nvarchar(max)') as [Attr2],
x.i.value('./@Attr3', 'nvarchar(max)') as [Attr3],
x.i.value('./@Attr4', 'nvarchar(max)') as [Attr4],
x.i.value('./@Attr5', 'nvarchar(max)') as [Attr5],
x.i.value('./@Attr6', 'nvarchar(max)') as [Attr6],
x.i.value('./@Attr7', 'nvarchar(max)') as [Attr7],
x.i.value('(./Elem3/text())[1]', 'nvarchar(max)') as [Elem3],
x.i.value('(./Elem4/text())[1]', 'nvarchar(max)') as [Elem4],
x.i.value('(./Elem5/text())[1]', 'nvarchar(max)') as [Elem5],
x.i.value('(./Elem6/text())[1]', 'nvarchar(max)') as [Elem6],
...
x.i.value('(./Elem200/text())[1]', 'nvarchar(max)') as [Elem200]
FROM [XmlLoad].[DataTable] as t
CROSS APPLY t.[Xml].nodes('./Log') as x(i);
XML列的示例内容是:
<Log Id="1" Attr1="a" Attr2="a" Attr3="a" Attr4="a" Attr5="a" Attr6="a" Attr7="a" >
<Elem1>value</Elem1>
<Elem2>value</Elem2>
<Elem3>value</Elem3>
<Elem4>value</Elem4>
<Elem5>value</Elem5>
<Elem6>value</Elem6>
...
<Elem200>value</Elem200>
</Log>
SQL服务器做的是为每个元素创建一个嵌套循环,这给出了疯狂的执行计划。当我提取10个元素时,这不是问题,但对于200,这非常慢。
我尝试过主要和次要的XML索引,性能变得更糟,我也尝试将解析更改为:
x.i.value('(./Log/Elem1/text())[1]', 'nvarchar(max)') as [Elem1],
没有CROSS APPLY但执行计划是相同的。 执行计划是...... part of execution plan
完整计划看起来像这样:) full execution plan
有什么方法可以改善吗?我应该以某种方式重建查询吗?