Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Get comma separated column names from a table

Posted on 2015-01-30
5
Medium Priority
?
146 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
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 71

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 1000 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 14

Accepted Solution

by:
Nakul Vachhrajani earned 1000 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

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

926 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