Pierre-Alain Vigeant
Pierre-Alain Vigeant

Reputation: 23083

How to returns the text() of an xml value with a space between the nodes value?

In SQL Server 2008 R2,

Considering the following xml

DECLARE @xml xml = '<data><fr>Chambre standard</fr><en>Standard room</en></data>';

How can I return the following string:

Chambre standard Standard room

Currently, I'm only able to return the string concatenated together without any space by using

SELECT @xml.query('//*/text()').value('.', 'varchar(max)')

Which return

Chambre standardStandard room

But I need to insert a space in there.

How could I insert a space between the node text?

Upvotes: 1

Views: 1633

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

You can use .nodes() to shred your XML.

select T.N.value('local-name(.)', 'varchar(128)') as Name,
       T.N.value('.', 'varchar(max)') as Value
from @xml.nodes('/data/*') as T(N);

Result:

Name  Value
fr    Chambre standard
en    Standard room

Then you can use for xml path('') to bring it back together.

select stuff((select ' '+T.N.value('.', 'varchar(max)')
              from @xml.nodes('/data/*') as T(N)
              for xml path(''), type).value('.', 'varchar(max)'), 1, 1, '')

Result:

(No column name)
Chambre standard Standard room

Upvotes: 2

Related Questions