Get comma separated column names from a table

How can I set a string to a comma separated list of columns. I am using SQL Server 2008

example

@ColumnNames =  'Col1, Col2, Col3'
LVL 1
countrymeisterAsked:
Who is Participating?
 
Nakul VachhrajaniConnect With a Mentor Technical Architect, Capgemini IndiaCommented:
Based on your requirement, you can use any one of the methods highlighted here: Different Ways to generate Comma-separated string

Do go through the various comments in my post as well - there is some great information with respect to string manipulation there.
0
 
Mike EghtebasDatabase and Application DeveloperCommented:
What you have is correct. But how it is used matters. Show more. Give a bigger picture.
0
 
QlemoDeveloperCommented:
You can only use that in a dynamic query, that is the SQL as string, ran with EXEC or sp_executesql.
0
 
Aneesh RetnakaranDatabase AdministratorCommented:
0
 
Monika BhartiConnect With a Mentor Sr. AnalyticsCommented:
Hi,

To set a string with comma separated list of columns use the following code. Before running this code you can change the table name, which you are using.

USE AdventureWorks
GO
-- Check Table Column
SELECT [Name]
FROM HumanResources.Shift
GO
-- Get CSV values
SELECT STUFF(
(SELECT ',' + s.Name
FROM HumanResources.Shift s
ORDER BY s.Name
FOR XML PATH('')),1,1,'') AS CSV
GO

Open in new window


Hope this will resolve your query.
0
All Courses

From novice to tech pro — start learning today.