Friday, July 1, 2011

Comma seperated values using SQL Server using Query...

How to get comma seperated string from table.
I have table called TableName and I have colum name "Age"
Using simple query I get 
Age 
===
12
23
45
56
67
78
78
but I want the output like this
12,23,45,56,67,78,78
Then use this query to get output in this format...


You can use this query but first comma will be display...
========================================
 select ', ' + columname from -- create comma separated values
(
 select  ColumName from TableName--Your query here
 ) AS T FOR XML PATH('')

OR

If you want to remove first comma also then use this query
========================================
select  STUFF(
(
 select ', ' + ColumName from -- create comma separated values
(
 select  ColumName from TableName--Your query here
 ) AS T FOR XML PATH('')
)
,1,1,'') AS [Name]

No comments:

Post a Comment

Share your thoughts....