Convert table to CSV string in SQL Server

There doesn’t seem to be a native function in SQL Server to collapse a table of row values into a comma-separated string, for example:

Animal
Llama
Manatee
Pygmy Marmoset
Okapi

Result CSV: “Llama, Manatee, Pygmy Marmoset, Okapi”

In mySQL there’s a built-in aggregate function called group_concat, but no equivalent in SQL Server unless you build your own .NET function, like in this TechNet article Invoking CLR User-Defined Aggregate Functions. That’s quite a chunk of coding and is restricted to SQL Server 2005 or later, so here’s a handy SQL snippet that does a similar job without the fuss.

select Name from Animal

declare @csv varchar(max)
select @csv = coalesce(@csv + ‘, ‘, ”) + Name from Animal
select @csv

If you use the code regularly then consider creating a scalar user-defined function (UDF) that returns the CSV string as varchar.

10 Responses to “Convert table to CSV string in SQL Server”

  1. Christian Says:

    Awesome. Just what I was looking for.

  2. Axis Says:

    Very helpful post!

  3. Mark Paulsen Says:

    Thank you very much for your post! This is a very clean way to convert the data in a table column into a single string.

    For others reviewing this post, note that the string being appended to @csv above -> ‘, ‘, ” is:
    1) a single quote
    2) a comma
    3) a space
    4) a single quote
    5) a comma
    6) a space
    7) two single quotes

    NOTE: single quotes are used to delimit strings in SQL

  4. Jayasabari Says:

    Ya it’s working…….

    Thanks

  5. Facundo Báez Says:

    Good Post! Thanks

  6. waqar mir Says:

    wow … i was looking for this ….:)
    thanks

  7. nbnew25 Says:

    Thank you very much.
    It very good ^^

  8. Amanda Says:

    I could only create a list of varchar elements, what about a list of int?

  9. Kyle Says:

    SUUUUPER handy, I never would have thought of that. Thanks a lot.

    Amanda: I too need a list of ints so I’ve modified it a bit to turn the ints into strings
    select @csv = coalesce(@csv + ‘, ‘, ”) + LTRIM(STR(AnimalID)) from Animals

  10. Gordon Says:

    Here’s a faster variant of the code you gave:

    DECLARE @Csv NVARCHAR(MAX)
    SET @Csv = ”
    SELECT @Csv = @Csv + COALESCE(Name, ”) + ‘,’
    FROM Animals
    SET @Csv = SUBSTRING(@Csv 1, LEN(@Csv) – 1)
    SELECT @Csv

    …and another even faster, albeit hacky variant:
    DECLARE @Csv NVARCHAR(MAX)
    SELECT @Csv =
    (
    SELECT COALESCE(Name, ”) + ‘,’
    FROM Animal
    FOR XML PATH(”)
    )
    SET @Csv = SUBSTRING(@Csv, 1, LEN(@Csv) – 1)
    SELECT @Csv

    (I’m using SQL Server 2005)


Leave a Reply