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"
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.
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 | 
                        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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With