我有一个XML
<applicationbuilds xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="https://analysiscenter.veracode.com/schema/2.0/applicationbuilds" xsi:schemaLocation="https://analysiscenter.veracode.com/schema/2.0/applicationbuilds https://analysiscenter.veracode.com/resource/2.0/applicationbuilds.xsd" >
<application app_name="Architecture" app_id="15439">
<build version="V 2.0" build_id="16158">
</build>
</application>
</applicationbuilds>
我使用以下查询从下面的查询中选择xml中的appid,build_id和版本。
;WITH XMLNAMESPACES(DEFAULT 'https://analysiscenter.veracode.com/schema/2.0/applicationbuilds')
SELECT
Y.ID.value('../@app_id', 'varchar(max)') as app_id,
Y.ID.value('@build_id', 'varchar(max)') as build_id,
Y.ID.value('@version', 'varchar(max)') as build_name
FROM @XML.nodes('//applicationbuilds/application/build') as Y(ID)
虽然它工作正常,但查询返回结果集需要很长时间。如果我只是避免这一行
Y.ID.value('../@app_id', 'varchar(max)') as app_id,
运行查询只需不到一秒钟。所以上面的代码行导致了延迟。在不造成太多延迟的情况下获取app_id的最佳方法是什么?
SQL小提琴链接:http://sqlfiddle.com/#!3/d41d8/19883 感谢
答案 0 :(得分:2)
取决于“应用程序”和“构建”元素的数量。
只有一个'application'元素和一个'build'元素:
;WITH XMLNAMESPACES(DEFAULT 'https://analysiscenter.veracode.com/schema/2.0/applicationbuilds')
SELECT
Y.ID.value('@app_id', 'varchar(max)') as app_id,
Y.ID.value('(build/@build_id)[1]', 'varchar(max)') as build_id,
Y.ID.value('(build/@version)[1]', 'varchar(max)') as build_name
FROM @XML.nodes('(/applicationbuilds/application)[1]') as Y(ID)
许多'应用'和'构建'元素:
;WITH XMLNAMESPACES(DEFAULT 'https://analysiscenter.veracode.com/schema/2.0/applicationbuilds')
SELECT
Y.ID.value('@app_id', 'varchar(max)') as app_id,
Z.Z.value('@build_id', 'varchar(max)') as build_id,
Z.Z.value('@version', 'varchar(max)') as build_name
FROM @XML.nodes('/applicationbuilds/application') as Y(ID)
CROSS APPLY Y.ID.nodes('build')Z(Z)