Solved

Get comma separated column names from a table

Posted on 2015-01-30
5
113 Views
Last Modified: 2015-04-07
How can I set a string to a comma separated list of columns. I am using SQL Server 2008

example

@ColumnNames =  'Col1, Col2, Col3'
0
Comment
Question by:countrymeister
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
5 Comments
 
LVL 34

Expert Comment

by:Mike Eghtebas
ID: 40580806
What you have is correct. But how it is used matters. Show more. Give a bigger picture.
0
 
LVL 69

Expert Comment

by:Qlemo
ID: 40580854
You can only use that in a dynamic query, that is the SQL as string, ran with EXEC or sp_executesql.
0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 40580855
0
 
LVL 4

Assisted Solution

by:Monika Bharti
Monika Bharti earned 250 total points
ID: 40581144
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
 
LVL 13

Accepted Solution

by:
Nakul Vachhrajani earned 250 total points
ID: 40582826
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

Featured Post

Edgartown IT Case Study

Learn about Edgartown's quest to ensure the safety and security of the entire town's employee and citizen data. Read the case study!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question