Comma Delimited List with COALESCE

There may be a day when you need to create your own comma delimited list from data contained in a SQL table.  Sure you could build a cursor and go through each row adding a comma after each record.  The good news is that there is an alternative.  The better news is that this method is easier, faster and takes MUCH less code.  COALESCE in SQL has many uses and building a list is one of them.  To do this in our context use the following format: COALESCE(@Variable + DelimiterWhatToDoWhenThereAreNoMoreResults)  The following code will bring back a list of all the states in my State table adding a comma after each one.  We want a comma delimiter and when there are no more results we want to end with nothing so we don’t have a trailing comma.  Therefore we will use COALESCE(@State + ‘, ‘, ”).  Now we just need to build a SQL statement around that to add a state name to the end of the string each time a new one is found.  The following code will accomplish that task.  @State will start out empty so no comma will be added to it but the first state name will populate the variable.  Each subsequent state name will have a comma added before it thanks for the COALESCE function being before the state name that is selected next.
DECLARE @State varchar(800)
SELECT @State = COALESCE(@State + ‘, ‘, ”) + StateName
FROM State
Select @State
Now you can build your own delimited lists!

About the author

Bradley Schacht

Bradley Schacht is a Senior Program Manager on the Microsoft Azure Synapse Analytics team based in Jacksonville, FL. He has worked with Microsoft SQL Server and Azure data services since 2009 as a consultant, trainer, and architect. He has co-authored 4 SQL Server and Power BI books, most recently the Microsoft Power BI Quick Start Guide. Bradley enjoys solving interesting problems and teaching others to use new technology. He frequently presents at community events around the country, is a contributor to sites such as SQLServerCentral.com, and is a member of the Jacksonville SQL Server User Group (JSSUG).

Add comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Bradley Schacht

Bradley Schacht is a Senior Program Manager on the Microsoft Azure Synapse Analytics team based in Jacksonville, FL. He has worked with Microsoft SQL Server and Azure data services since 2009 as a consultant, trainer, and architect. He has co-authored 4 SQL Server and Power BI books, most recently the Microsoft Power BI Quick Start Guide. Bradley enjoys solving interesting problems and teaching others to use new technology. He frequently presents at community events around the country, is a contributor to sites such as SQLServerCentral.com, and is a member of the Jacksonville SQL Server User Group (JSSUG).

Follow Me

Thumbnails managed by ThumbPress