我有一个XML变量,我需要在SQL中查询并为每个值返回一行:
declare @info xml
select @info = '<parameters><locality_id>303</locality_id><locality_id>PC_303</locality_id></parameters>'
参数节点可以有1个或更多locality_id值(在上面的例子中为2) 输出应为
locality_id
303
PC_303
我得到了两行作为结果,但是值没有正确显示,它只显示第一个值两次:
declare @info xml
select @info = '<parameters><locality_id>303</locality_id><locality_id>PC_303</locality_id></parameters>'
select feed.x.value('(//locality_id)[1]','NVARCHAR(255)')
from @info.nodes('//parameters/locality_id') feed(x)
我怎样才能得到我们需要的东西?
答案 0 :(得分:3)
问题在于(//locality_id)[1]
,它说的是“让我获得任何级别的第一个locality_id”。由于您已经使用nodes
方法选择了所需的节点,因此您只需使用.
从当前上下文中选择值。
declare @info xml
select @info = '<parameters><locality_id>303</locality_id><locality_id>PC_303</locality_id></parameters>'
select feed.x.value('.','NVARCHAR(255)')
from @info.nodes('//parameters/locality_id') feed(x)