John Kiernander
John Kiernander

Reputation: 4904

Concatenating Values Within SQL XML field

I have a table in SQL Server 2012 which has an XML field. The field contains arrays (the number of elements is not constant) in the following format:

<values>
    <value>A</value>
    <value>B</value>
    <value>C</value>
    <value>D</value>
</values>

and I would like to turn it into a varchar like this:

'A;B;C;D'

I have tried:

SELECT myField.value('.', 'NVARCHAR(50)')
FROM   myTable

which creates 'ABCD' but I don't know how to delimit it (In the real case they are not single character values).

Upvotes: 2

Views: 98

Answers (2)

bvr
bvr

Reputation: 4826

Try this

DECLARE @myTable TABLE (id int,myField XML)

INSERT INTO @myTable(id,myField) VALUES(1,'<values>
    <value>A</value>
    <value>B</value>
    <value>C</value>
    <value>D</value>
</values>')


;WITH xmltable
AS
(
    SELECT id, myField.v.value('.', 'varchar(200)') AS myField
    FROM @myTable 
    CROSS APPLY myField.nodes('/values/value') AS myField(v)
)

SELECT STUFF((SELECT ';' + myField 
                  FROM xmltable t2 
                  WHERE t2.id = t1.id  
                  FOR XML PATH('')),1,1,'') AS myField
FROM xmltable t1
GROUP BY id

Upvotes: 1

John Kiernander
John Kiernander

Reputation: 4904

I've thought of a hack to achieve this...

SELECT REPLACE(
           REPLACE(
               REPLACE(
                   CAST([myField] As NVARCHAR(MAX)), 
                   '<values><value>', 
                   ''), 
               '</value></values>', 
               ''), 
           '</value><value>', 
           ';'
       ) As [Hacked] 
FROM   [myTable]

...but it makes me feel a bit dirty. There has to be a better way.

Upvotes: 0

Related Questions