Click here to Skip to main content
15,893,663 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a table emp which contain 1 column as ID and there is 4 record in table as 1,2,3,4
when i run command select * from emp Result is
ID
1
2
3
4

But i wants co convert result in this Format using sql server.
ID:1,2,3,4


Thanks in Advance.
Posted

Try this:
SQL
DECLARE @XYList AS varchar(MAX) -- Leave as NULL

SELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(nvarchar(20), ID)+ ',' 
FROM emp
 
Share this answer
 
v2
Comments
Manas Bhardwaj 6-Aug-13 14:53pm    
Correct. +5!
Kuthuparakkal 6-Aug-13 21:39pm    
Thanks!
rajerra 11-Jul-14 8:28am    
DECLARE @XYList AS varchar(MAX) -- Leave as NULL

SELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(nvarchar(20), ID)
FROM emp
Something like this:

Select (Stuff((Select ', ' + FName From Accounts FOR XML PATH('')),1,2,''))


Btw, did you try to google for this? I posted the following link years ago :)

http://manasbhardwaj.net/get-column-values-as-comma-seperated-string/[^]
 
Share this answer
 
Comments
Maciej Los 6-Aug-13 17:55pm    
+5
Manas Bhardwaj 7-Aug-13 2:27am    
thx!
If you are using is higher than the SQL2000 version, you can use FOR XML PATH.But if you Use Sql2000.
like this :
SQL
declare @s varchar(8000)
set @s = ''
select @s = @s + cloumnname + ',' from tablename where ...
set @s = stuff(@s,len(@s),1,'')
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900