Monday, April 8, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...