patternsqlModerate
Concatenate all values of the same XML element using XPath/XQuery
Viewed 0 times
xquerysamethexpathallxmlconcatenateelementusingvalues
Problem
I have an XML value like this:
I want to concatenate all
Now I know that I can shred the XML, aggregate the results back as a nodeless XML, and apply
However, I would like to do all that using XPath/XQuery methods only, something like this:
Is there such a way?
The reason I am looking for a solution in this direction is because my actual XML contains other elements too, for instance:
And I would like to be able to extract both the
A
B
C
...
I want to concatenate all
I values and return them as a single string: ABC....Now I know that I can shred the XML, aggregate the results back as a nodeless XML, and apply
.values('text()[1]', ...) to the result:SELECT
(
SELECT
n.n.value('text()[1]', 'varchar(50)') AS [text()]
FROM
@MyXml.nodes('/R/I') AS n (n)
FOR XML
PATH (''),
TYPE
).value('text()[1]', 'varchar(50)')
;However, I would like to do all that using XPath/XQuery methods only, something like this:
SELECT @MyXml. ? ( ? );Is there such a way?
The reason I am looking for a solution in this direction is because my actual XML contains other elements too, for instance:
A
B
C
...
X
Y
Z
...
And I would like to be able to extract both the
I values as a single string and the J values as a single string without having to use an unwieldy script for each.Solution
This might work for you:
It picks up all
If you just want all
If you want the values for
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)')Code Snippets
select @MyXml.value('/R[1]', 'varchar(50)')select @MyXml.value('.', 'varchar(50)')select @MyXml.query('/R/I/text()').value('.', 'varchar(50)'),
@MyXml.query('/R/J/text()').value('.', 'varchar(50)')Context
StackExchange Database Administrators Q#237475, answer score: 11
Revisions (0)
No revisions yet.