2

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).

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

That works thanks, I was hoping for something simpler but I'm beginning to think it isn't possible.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.