參考﹕--建表
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,

解决方案 »

  1.   

    hdhai9451(※★開拓者...前進☆※) ( ) 函数是最好的解决办法。。如果用一条SQL 可能只能得到一条记录。。通过参数传递declare @s as varchar(8000)
    set @s=''
    select @s=@s+','+ltrim(rtrim(a)) from 
    (
    select id,a from TABLE3 where id='1'  group by id,a --ID='1' 时候
    ) xset @s=case when (@s='') then '' else stuff(@s,1,1,'') endselect @s结果:
    ----------------------------
    aa,bb,cc
    (所影响的行数为 1 行)declare @s as varchar(8000)
    set @s=''
    select @s=@s+','+ltrim(rtrim(a)) from 
    (
    select id,a from TABLE3 where id='2'  group by id,a --ID='2' 时候
    ) xset @s=case when (@s='') then '' else stuff(@s,1,1,'') endselect @s结果:
    ----------------------------
    dd,ee(所影响的行数为 1 行)
      

  2.   

    我刚问过的问题, 你参考一下:
    http://community.csdn.net/Expert/topic/3563/3563642.xml?temp=.4707453