Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn one column of a table into a csv string in SQL Server without using a cursor

I want to return the results of select Column from Table into a comma separated string using SQL Server.

The column in question is rather large (nvarchar(2000)) so the solution has to be able to handle very large result values.

like image 717
Kyle West Avatar asked Jan 18 '09 16:01

Kyle West


People also ask

How can I get only column names from a table in SQL?

In SQL Server, you can select COLUMN_NAME from INFORMATION_SCHEMA. COLUMNS .


1 Answers

STRING_AGG was added in sql 2017

https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017

SELECT STRING_AGG (ColumnName, ',') AS csv  FROM TableName GROUP BY ColumnName2 
like image 52
Nathan Smith Avatar answered Sep 24 '22 03:09

Nathan Smith