我想从我的 xml 文档中的每个 session 中获取所有读取节点及其值,并从父节点获取 session ID。我在 SQL Server 2008 实例上运行它。
我的 xml 设置是:
<Sessions>
<SessionID>99</SessionID>
<Readings>
<Reading>
<Point>
<Lat>-40.411558</Lat>
<Lng>175.63504</Lng>
</Point>
<Heading>54</Heading>
<Speed>0.1</Speed>
<Height>0</Height>
<FlowRate>0.69</FlowRate>
<AppRate>74</AppRate>
</Reading>
... more readings
</Readings>
<Sessions>
我最初的尝试(有效)如下所示,但是当我运行它时,这似乎非常慢。但是,当我取出添加 SessionID 即 ../../SessionID 的行时,它似乎执行得更快。将 12 秒的查询时间缩短为 2 秒。
SELECT
[SessionID] = c.value('(../../SessionID)[1]', 'int'),
[Heading] = c.value('(Heading)[1]', 'float'),
[Speed] = c.value('(Speed)[1]', 'float'),
[Height] = c.value('(Height)[1]', 'float'),
[FlowRate] = c.value('(FlowRate)[1]', 'float'),
[AppRate] = c.value('(AppRate)[1]', 'float'),
[Latitude] = c.value('(Point/Lat)[1]', 'float'),
[Longtitude] = c.value('(Point/Lng)[1]', 'float')
FROM
@XMLData.nodes('/Sessions/Readings/Reading') XMLData(c)
无论如何,我可以在不需要使用 ../../符号引用 SessionID 的情况下做到这一点。我确实需要 SessionID,因为此查询用于将记录插入到临时表中:
insert into #MyTempTable
SELECT
[SessionID] = c.value('(../../SessionID)[1]', 'int'),
[Heading] = c.value('(Heading)[1]', 'float'),
[Speed] = c.value('(Speed)[1]', 'float'),
[Height] = c.value('(Height)[1]', 'float'),
[FlowRate] = c.value('(FlowRate)[1]', 'float'),
[AppRate] = c.value('(AppRate)[1]', 'float'),
[Latitude] = c.value('(Point/Lat)[1]', 'float'),
[Longtitude] = c.value('(Point/Lng)[1]', 'float')
FROM
@XMLData.nodes('/Sessions/Readings/Reading') XMLData(c)
最佳答案
对于避免 ../../的第一部分,您可以使用 CROSS APPLY 来提供两个数据集。
此外,如果您想要更快的 INSERT 并且不担心日志记录,SELECT INTO 语句将提供更快的插入:
SELECT
s.value('(SessionID)[1]', 'int') SessionID,
r.value('(Heading)[1]', 'float') Heading,
r.value('(Speed)[1]', 'float') Speed,
r.value('(Height)[1]', 'float') Height,
r.value('(FlowRate)[1]', 'float') FlowRate,
r.value('(AppRate)[1]', 'float') AppRate,
r.value('(Point/Lat)[1]', 'float') Latitude,
r.value('(Point/Lng)[1]', 'float') Longtitude
INTO #Reading
FROM
@XMLData.nodes('/Sessions') as S(s)
CROSS APPLY
s.nodes('./Readings/Reading') XMLData(r)
关于sql - 使用 ../../<node name> 引用父节点时,XPath 查询运行缓慢,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10524901/