SQL SERVER: concatenate node values of XML column

624 Views Asked by At

I have the following table that holds a column which is in XML:

Id Label Details
1 Test1 <terms><destination><email>[email protected]</email><email>[email protected]</email></destination><content>blabla</content></terms>
2 Test2 <terms><destination><email>[email protected]</email><email>[email protected]</email></destination><content>blabla</content></terms>

I would like a query that produces the following output:

Any clue on how I can concat the XML email node values as a column along the related columns (Id and Label)? Thanks ahead

2

There are 2 best solutions below

0
On BEST ANSWER
select ID, Label,
    stuff(
        details.query('for $step in /terms/destination/email/text() return concat(", ", string($step))')
        .value('.', 'nvarchar(max)'),
    1, 2, '')
from @tbl;
0
On

Please try the following solution.

Because DDL and sample data population were not provided, assumption is that the Details column is of XML data type.

SQL

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, Label VARCHAR(20), Details XML);
INSERT INTO @tbl (Label, Details) VALUES
('Test1',N'<terms><destination><email>[email protected]</email><email>[email protected]</email></destination><content>blabla</content></terms>'),
('Test2',N'<terms><destination><email>[email protected]</email><email>[email protected]</email></destination><content>blabla</content></terms>');
-- DDL and sample data population, end

SELECT ID, Label 
    , REPLACE(Details.query('data(/terms/destination/email/text())').value('.','VARCHAR(MAX)'), SPACE(1), ', ') AS Destination
FROM @tbl;

Output

+----+-------+----------------------------------+
| ID | Label |           Destination            |
+----+-------+----------------------------------+
|  1 | Test1 | [email protected], [email protected] |
|  2 | Test2 | [email protected], [email protected] |
+----+-------+----------------------------------+