.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> SQL Query >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Comma separated values without using For XML Path

Posted By:shankey       Posted Date: July 01, 2011    Points: 60    Category: SQL Query    URL: http://www.dotnetspark.com  

Comma separated values without using For XML Path
 

Comma separated values without using For XML Path.


The easiest way to get all values of a column as comma separated values and use it in some query is as follow:

Create a table with name and age field and insert some values:


CREATE TABLE #tmp(NAME VARCHAR(255),Age INT)
INSERT INTO #tmp
(NAME, Age)
SELECT 'Mack',23
UNION ALL
SELECT 'Shankey'  ,25
UNION ALL
SELECT 'Maverick',26

Executing query to fetch comma separated names from the table


DECLARE @commaSeparated VARCHAR(MAX)
SET @commaSeparated = ''
SELECT
  @commaSeparated = name+ ',' + @commaSeparated
FROM
  #tmp
SELECT
  @commaSeparated
PRINT SUBSTRING(@commaSeparated,0,LEN(@commaSeparated))

Output




     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend