Skip to main content

Get CSV list of table columns in SQL Server.

--
-- Get a CSV list of columns in a table
--

declare @tablename as sysname = 'TABLE_NAME';

select replace(reverse(stuff(reverse((select   name + ',' as [data()]
                                      from     sys.columns
                                      where    object_name(object_id) = @tablename
                                      order by column_id
                                      for      xml path (''))), 1, 1, '')), ' ', '');

--
-- A bit better... this example won't include the leading comma like the statement above:
select csvList = cast(
    stuff(
            (
                -- BEGIN query to select the column to convert to CSV
                select ', ' + '''' + convert(varchar(50), Id) + ''''
                from dbo.UserProfiles
                where Id is not null
                -- END query to select the column to convert to CSV
                for xml path('')
            ), 1, 1, ''
         ) as varchar(max));