Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

|column| -------- |  1   | |  3   | |  5   | |  9   | 

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

like image 931
eddy ed Avatar asked Apr 24 '13 13:04

eddy ed


People also ask

What does convert () do in SQL?

In SQL Server (Transact-SQL), the CONVERT function converts an expression from one datatype to another datatype. If the conversion fails, the function will return an error. Otherwise, it will return the converted value. TIP: Use the TRY_CONVERT function to return a NULL (instead of an error) if the conversion fails.


2 Answers

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  | RESULTS | ----------- | 1,3,5,9 | 
like image 169
Kaf Avatar answered Oct 13 '22 22:10

Kaf


There is new method in SQL Server 2017:

SELECT STRING_AGG (column, ',') AS column FROM Table;

that will produce 1,3,5,9 for you

like image 28
jkalamarz Avatar answered Oct 13 '22 21:10

jkalamarz