SQL Parse XML String into rows of a table
I have an XML variable which I need to query in SQL and return a row for each value:
declare @info xml
select @info = '<parameters><locality_id>303</locality_id><locality_id>PC_303</locality_id></parameters>'
There parameters node can have 1 or more locality_id values (2 in the case above) The output should be
locality_id
303
PC_303
I have gotten as far as getting two rows as the result, but the values are not coming up properly, it just shows the first value twice:
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)
How can i get what we nee开发者_StackOverflowd for this?
The problem is in (//locality_id)[1]
which is saying "get me the first locality_id at any level". Since you are already selecting the nodes you need with the nodes
method, you can just select the value from the current context using .
.
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)
精彩评论