declare @id int
set @id=0
declare @temp table(id int,n varchar(10))
while(@id<3)
begin
set @id=@id+1
declare @all nvarchar(500)
set @all=''
select @all=@all+ n + ',' from t2 where [id]=@id
insert into @temp values (@id,substring(@all,l,len(@all)-1))
end
select * from @temp
set @id=0
declare @temp table(id int,n varchar(10))
while(@id<3)
begin
set @id=@id+1
declare @all nvarchar(500)
set @all=''
select @all=@all+ n + ',' from t2 where [id]=@id
insert into @temp values (@id,substring(@all,l,len(@all)-1))
end
select * from @temp
set @id=0
select @max=max(id) from t1
declare @temp table(id int,n varchar(10))
while(@id<@max)
begin
set @id=@id+1
if exists(select * from t1 where id=@id)
begin
declare @all nvarchar(500)
set @all=''
select @all=@all+ n + ',' from t2 where [id]=@id
insert into @temp values (@id,substring(@all,l,len(@all)-1))
end
end
select * from @temp
create table tb (A varchar(10),B varchar(1000))
Insert into tb
select '111','AA0000,AA0001,AA0002,'
union all select '111','BB0000,BB0001,BB0002,'
union all select '222','AA0120,AA0102,AA1453,'
union all select '222','BB1212,BB3423,BB2123,'select * from tb--函數
create function dbo.fn_b(@a varchar(10))
returns varchar(1000)
as
begin
declare @s varchar(1000)
set @s=''
select @s=@s+[B] from tb where A=@a
return (@s)
end--刪除
drop table tb
drop function dbo.fn_b--結果
select A,B=dbo.fn_b(A) from tb group by A
A B
-------------------------------------------
111 AA0000,AA0001,AA0002,BB0000,BB0001,BB0002,
222 AA0120,AA0102,AA1453,BB1212,BB3423,BB2123,
create table t2(id int,n varchar(20))
insert t1 values (1)
insert t1 values (2)
insert t1 values (3)insert t2 values (1,'a')
insert t2 values (1,'b')
insert t2 values (1,'c')
insert t2 values (2,'d')
insert t2 values (2,'e')
insert t2 values (2,'f')
insert t2 values (3,'g')
insert t2 values (3,'h')
insert t2 values (3,'i')select * from t1
select * from t2--函數
create function dbo.fn_t(@a int)
returns varchar(1000)
as
begin
declare @s varchar(1000)
set @s=''
select @s=@s+[n]+',' from t2 where id=@a
return (left(@s,len(@s)-1))
enddrop table t1,t2
drop function dbo.fn_tselect id,n=dbo.fn_t(id) from t2 group by id結果
id n
------------------
1 a,b,c
2 d,e,f
3 g,h,i