Discussion:
Convert rows into a "string of columns"
(too old to reply)
a***@webmail.co.za
2013-04-24 14:02:36 UTC
Permalink
Using MSSQL 2008 R2 this query:

SELECT tblusers.id
FROM tblusers
WHERE tblusers.name = 'smith'

gives me a few rows:

id
123
678
987

How do I convert that column into a string containing a coma separated list of the id's? Example:

123,678,987

Thanks
Erland Sommarskog
2013-04-24 22:12:34 UTC
Permalink
Post by a***@webmail.co.za
SELECT tblusers.id
FROM tblusers
WHERE tblusers.name = 'smith'
id
123
678
987
How do I convert that column into a string containing a coma separated
123,678,987
; WITH CTE (list) AS (
SELECT ltrim(str(id)) + ','
FROM tblusers
WHERE name = 'smith'
FOR XML PATH('')
)
SELECT substring(list, 1, len(list) - 1)
FROM CTE
--
Erland Sommarskog, SQL Server MVP, ***@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
Andy Dufresne
2013-04-25 14:07:06 UTC
Permalink
Post by Erland Sommarskog
; WITH CTE (list) AS (
SELECT ltrim(str(id)) + ','
FROM tblusers
WHERE name = 'smith'
FOR XML PATH('')
)
SELECT substring(list, 1, len(list) - 1)
FROM CTE
Thanks Erland. I was thinking along the lines of a CTE... Very powerful, if you know how to do it! Thanks.
Continue reading on narkive:
Loading...