Mladen Prajdić Blog

Blog about stuff and things and stuff. Mostly about SQL server and .Net

SQL Server 2005: Concat values XML Style

A few days ago i showed how to split string with XML.

Now it's time for concatenation with XML.

 

DECLARE @t TABLE (col VARCHAR(10))

INSERT into @t select 'aaaa' UNION ALL select 'bbbb' UNION ALL select 'cccc' UNION ALL select null UNION ALL select 'dddd'

SELECT * FROM @t

SELECT ( SELECT col + ', ' as [text()] FROM @t ORDER BY col DESC FOR XML PATH('') ) AS MyCsvList

Both of these (split and concat) methods aren't really anything special. They're just a new way of solving old problem.

But whenever i need them i have to look them up, so where else to keep them handy than here, right? :)

 


kick it on DotNetKicks.com

Legacy Comments


Denis the SQL Menace
2007-06-01
re: SQL Server 2005: Concat values XML Style
If you want to get rid of the last comma

SELECT LEFT(MyCsvList,LEN(MyCsvList)-1)
FROM (SELECT
(
SELECT col + ', ' as [text()]
FROM @t
ORDER BY col DESC
FOR XML PATH('')
) AS MyCsvList) z


Denis

Mladen
2007-06-01
re: SQL Server 2005: Concat values XML Style
thanx D-Man :)

I usually just trim it on the client, though.

Denis the SQL Menace
2007-06-01
re: SQL Server 2005: Concat values XML Style
Yes, because we all know what Celko says "Formatting should be done on the client" ;-)

Peso
2007-12-09
re: SQL Server 2005: Concat values XML Style
Also see
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=81254
for more formatting stuff with FOR XML PATH

Dejan
2008-10-14
re: SQL Server 2005: Concat values XML Style
Wow! You saved my life!

A
2008-11-14
re: SQL Server 2005: Concat values XML Style
Be careful with the For XML Path as it replaces charachters like < and > with &lt and &gt.