Concatenate all values of the same XML element using XPath/XQuery
This might work for you:
select @MyXml.value('/R[1]', 'varchar(50)')
It picks up all text()
elements from the first R
and below.
If you just want all text()
you can do
select @MyXml.value('.', 'varchar(50)')
If you want the values for I
and J
separate do this instead.
select @MyXml.query('/R/I/text()').value('.', 'varchar(50)'),
@MyXml.query('/R/J/text()').value('.', 'varchar(50)')
Depending on your actual XML structure you could consider using a loop like this:
DECLARE @xml XML
SELECT @xml = '<R>
<I>A</I>
<I>B</I>
<I>C</I>
<J>X</J>
<J>Y</J>
<J>Z</J>
</R>'
SELECT
Tbl.Col.query('for $i in I return $i').value('.', 'nvarchar(max)'),
Tbl.Col.query('for $i in J return $i').value('.', 'nvarchar(max)')
FROM @xml.nodes('R') Tbl(Col);
which outputs this:
(No column name) | (No column name)
--------------- | ---------------
ABC | XYZ
See this fiddle