June 2, 2016 at 3:55 am
Hi there,
Following code will do the job for me. But I wonder is there any other way to accomplish.
create table #t (id int , name varchar(100))
insert into #t values (1,'a')
insert into #t values (1,'b')
insert into #t values (2,'c')
insert into #t values (3,'a')
insert into #t values (3,'b')
insert into #t values (3,'c')
create table #t1 (id int , names varchar(100))
declare @a varchar(100) ,@i int =1
while (@i < = (select MAX(id ) from #t))
begin
set @a = ''
select @a = Coalesce(@a+',','')+name from #t where id = @i
insert into #t1 values (@i,substring(@a,2,LEN(@a)))
set @i = @i +1
end
Thanks
June 2, 2016 at 4:44 am
squvi.87 (6/2/2016)
Hi there,Following code will do the job for me. But I wonder is there any other way to accomplish.
create table #t1 (id int , names varchar(100))
declare @a varchar(100) ,@i int =1
while (@i < = (select MAX(id ) from #t))
begin
set @a = ''
select @a = Coalesce(@a+',','')+name from #t where id = @i
insert into #t1 values (@i,substring(@a,2,LEN(@a)))
set @i = @i +1
end
Thanks
You forgot the ddl for #t.
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
June 2, 2016 at 5:21 am
You forgot the ddl for #t.
added now
June 2, 2016 at 5:32 am
There are several ways to do this, most of them are compared here.
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
June 2, 2016 at 6:40 am
ChrisM@Work (6/2/2016)
There are several ways to do this, most of them are compared here.
I would suggest that you use the XML PATH option (unless you already use CLR). If you want an even easier way to write it, check the following: http://www.sqlservercentral.com/articles/SSMS/138994/
June 2, 2016 at 6:58 am
Luis Cazares (6/2/2016)
ChrisM@Work (6/2/2016)
There are several ways to do this, most of them are compared here.I would suggest that you use the XML PATH option (unless you already use CLR). If you want an even easier way to write it, check the following: http://www.sqlservercentral.com/articles/SSMS/138994/
That's pretty much the same conclusion reached by Mr Bertrand, Luis - and it gets my vote too 😉
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply