[英]Return all possible values from xQuery
I have the below code which returns repair costs if I manually select the specific instances eg[1],[2] etc. 我有以下代码,如果我手动选择特定实例,例如[1],[2]等,它将返回维修费用。
I wanted to know if it was possible to return all items dynamically 我想知道是否可以动态返回所有项目
select
*
,Data1.Data.value('(/PurchaseModel//DamageModel/Damage/RepairCost)[1]', 'Float')
,Data1.Data.value('(/PurchaseModel//DamageModel/Damage/RepairCost)[2]', 'Float')
,Data1.Data.value('(/PurchaseModel//DamageModel/Damage/RepairCost)[3]', 'Float')
,Data1.Data.value('(/PurchaseModel//DamageModel/Damage/RepairCost)[4]', 'Float')
,Data1.Data.value('(/PurchaseModel//DamageModel/Damage/RepairCost)[5]', 'Float')
,Data1.Data.value('(/PurchaseModel//DamageModel/Damage/RepairCost)[6]', 'Float')
,Data1.Data.value('(/PurchaseModel//DamageModel/Damage/RepairCost)[7]', 'Float')
FROM
#Data
You have to use dynamic SQL, here is how to construct such query once and then generate it automatically: 您必须使用动态SQL,这是一次构造此类查询然后自动生成查询的方法:
--you can omit declarations of these integers if you know limits of an index
declare @start int, @end int, @query nvarchar(1000)
select @start=1, @end=7, @query = 'select *'
--generate indexes that you want to retrieve
;with cte as (
select @start [n]
union all
select [n] + 1 from cte where n < @end
)
--construction of actual query, that you want to execute
select @query = @query + replace(', Data1.Data.value(''(/PurchaseModel//DamageModel/Damage/RepairCost)[@index]'', ''Float'')', '@index', cast(n as nvarchar(3))) from cte
sp_executesql @query + N' from #Data'
You can use the xml methods nodes and value like this: 您可以使用xml方法的节点和值,如下所示:
DECLARE @xml xml =
'<PurchaseModel>
<DamageModel>
<Damage>
<RepairCost>100.00</RepairCost>
<RepairCost>200.00</RepairCost>
<RepairCost>300.00</RepairCost>
<RepairCost>400.00</RepairCost>
<RepairCost>500.00</RepairCost>
<RepairCost>600.00</RepairCost>
<RepairCost>700.00</RepairCost>
<RepairCost>800.00</RepairCost>
<RepairCost>900.00</RepairCost>
<RepairCost>1000.00</RepairCost>
</Damage>
</DamageModel>
</PurchaseModel>'
select row.value('.','float') as repaircost
from @xml.nodes('(/PurchaseModel//DamageModel/Damage)') a(damage)
cross apply damage.nodes('RepairCost') bar(row)
This returns: 返回:
repaircost
----------
100
200
300
400
500
600
700
800
900
1000
With the following code you will have a Select command with all the values of the XML file. 使用以下代码,您将获得一个带有XML文件所有值的Select命令。 You could just insert it into some table afterwards.
之后,您可以将其插入到某个表中。
EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML
SELECT RankID,RankName,RankShort,@id
FROM OPENXML(@hDoc, '/PurchaseModel//DamageModel/Damage')
WITH ( RepairCost int 'RepairCost ')
EXEC sp_xml_removedocument @hDoc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.