eddy ed eddy ed - 1 year ago 71
SQL Question

SQL Server convert select a column and convert it to a string

Is it possible to write a statement that selects a column from a table and converts the results to a string?

Ideally I would want to have comma separated values.

For example, say that the SELECT statement looks something like

SELECT column
FROM table
WHERE column<10

and the result is a column with values

| 1 |
| 3 |
| 5 |
| 9 |

I want as a result the string "1, 3, 5, 9"

Kaf Kaf
Answer Source

You can do it like this:

Fiddle demo

declare @results varchar(500)

select @results = coalesce(@results + ',', '') +  convert(varchar(12),col)
from t
order by col

select @results as results

| 1,3,5,9 |
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download