Search code examples
sql-serverxmlqxmlquery

sql server - xml query - concat - adding space


I want to take a xml string and convert it to sql-table semicolon-delimitate

declare @x xml --for example
set @x = '<root><row><a>a1</a><b>b2</b></row><row><a>aa1</a><b>bb2</b></row></root>'
SELECT T.c.query('.').query('for $i in row/*/text() return concat($i,";")').value('.', 'nvarchar(max)') AS result  
FROM   @x.nodes('root/row') T(c)  

The Result:

a1; b2;
aa1; bb2;

The Result I want: (no space)

a1;b2;
aa1;bb2;

>> Bonus: Remove last semicolon

a1;b2
aa1;bb2

Thank You!


Solution

  • This can be done much easier:

    DECLARE @xml XML='<root>
      <row>
        <a>a1</a>
        <b>b2</b>
      </row>
      <row>
        <a>aa1</a>
        <b>bb2</b>
      </row>
    </root>';
    
    SELECT (
          STUFF(
          (
              SELECT ';' + v.value('.','nvarchar(max)')
              FROM r.nodes('*') AS B(v)
              FOR XML PATH('')
          ),1,1,'')
          )
    FROM @xml.nodes('/root/row') AS A(r)