SQL SERVER – Create a Comma Delimited List Using SELECT Clause From Table Column

I received following question in email : How to create a comma delimited list using SELECT clause from table column?

Answer is to run following script.


USE AdventureWorks
GO
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + Name
FROM Production.Product
SELECT @listStr
GO

Notepad++ showing output.txt with tab-delimited employee rows from a query

I have previously written a similar article where I have demonstrated this method using three sample examples. You can read the article for further information. SQL SERVER – Creating Comma Separate Values List from Table – UDF – SP

Here are few of the interesting articles related to this blog post:

Simple CSV implementations may prohibit field values that contain a comma or other special characters such as CSV. The CSV file format is not standardized. CSV is a common data exchange format that is widely supported by consumer, business, and scientific applications. CSV formats are best used to represent sets or sequences of records in which each record has an identical list of fields.

Want to try this yourself? Here is how to install AdventureWorks.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

CSV, Database, SQL Function, SQL Scripts, SQL Server, SQL Stored Procedure
Previous Post
SQL SERVER – Example of DISTINCT in Aggregate Functions
Next Post
Compound Assignment Operators in T-SQL with Simple Examples

Related Posts

109 Comments. Leave new

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.