create table table1(tlid int,f1 varchar(20))
insert into table1 select 1,'i1'
union select 2,'i2'
create table table2(t2id int,tlid int,d1 varchar(20))
insert into table2 select 1, 1, '你'
union select 2, 1, '你1'
union select 3, 2, '你2'
union select 4, 2, '你3'
union select 5, 2, '你4'
create proc p_t
as
begin
declare @t int,@d1 varchar(20)
select tlid,d1 as d3 into #t from table2 order by tlid,d1
update #t set d3=case when tlid=@t then @d1 else d3 end,@d1=case when tlid=@t then @d1+','+d3 else d3 end,@t=tlid
select tlid,max(d3) d3 from #t group by tlid
end
或者写个函数:
create function f_merg(@tlid varchar(100))
returns varchar(1000)
as
begin
declare @r varchar(1000)
set @r=''
select @r=@r+','+d1 from table2 where tlid=@tlid
set @r=stuff(@r,1,1,'')
return(@r)
end
go
select tlid,d3=dbo.f_merg(tlid) from table2 group by tlid
create function c_str(@t1id)
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s=''
select @s=@s+','+fmc from table2 where t1id=@t1id
return stuff(@s,1,1,'')
end
select t1id,dbo.c_str(t1id) from table2 group by t1id