Monday 8 April 2019

tsql - Convert multiple rows into one with comma as separator




If I issue SELECT username FROM Users I get this result:





username
--------
Paul
John
Mary


but what I really need is one row with all the values separated by comma, like this:





Paul, John, Mary


How do I do this?


Answer



This should work for you. Tested all the way back to SQL 2000.



create table #user (username varchar(25))


insert into #user (username) values ('Paul')
insert into #user (username) values ('John')
insert into #user (username) values ('Mary')

declare @tmp varchar(250)
SET @tmp = ''
select @tmp = @tmp + username + ', ' from #user

select SUBSTRING(@tmp, 0, LEN(@tmp))


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...