create table tb(ID int,comment varchar(20))
insert into tb select 1000,'coment1'
union all select 1000,'coment2'
union all select 10001,'comment1'
union all select 10001,'comment2'
union all select 10001,'comment3'
gocreate function dbo.fc_str(@ID int)
returns varchar(100)
as
begin
 declare @sql varchar(1000)
 set @sql=''
 select @sql=@sql+'/'+cast(comment as varchar(100)) from tb where ID=@ID
 return stuff(@sql,1,1,'')
end
goselect ID,dbo.fc_str(ID) as comment from tb group by ID
drop table tb
drop function dbo.fc_str

解决方案 »

  1.   

    for example--生成测试数据
    create table 表(部门 int,人员 varchar(20))
    insert into 表 select 1,'张三'
    insert into 表 select 1,'李四'
    insert into 表 select 1,'王五'
    insert into 表 select 2,'赵六'
    insert into 表 select 2,'邓七'
    insert into 表 select 2,'刘八'
    go--创建用户定义函数
    create function f_str(@department int)
    returns varchar(8000)
    as
    begin
        declare @ret varchar(8000)
        set @ret = ''
        select @ret = @ret+','+人员 from 表 where 部门 = @department
        set @ret = stuff(@ret,1,1,'')
        return @ret 
    end
    go
    --执行
    select 部门,人员=dbo.f_str(部门) from 表 group by 部门 order by 部门
    go--输出结果
    /*
    部门  人员
    ----  --------------
    1     张三,李四,王五
    2     赵六,邓七,刘八
    */
    --删除测试数据
    drop function f_str
    drop table 表
    go
      

  2.   

    create table t_test(id int,coment varchar(20))
    insert into t_test select 1000 ,'coment1'
    insert into t_test select 1000 ,'coment2'
    insert into t_test select 10001,'comment1'
    insert into t_test select 10001,'comment2'
    insert into t_test select 10001,'comment3'
    gocreate function f_str(@id int)
    returns varchar(100)
    as
    begin
        declare @ret varchar(100) 
        set @ret=''
        select @ret=@ret+'/'+coment from t_test where id=@id
        set @ret=stuff(@ret,1,1,'')
        return @ret
    end
    goselect id,dbo.f_str(id) coment from t_test group by id order by id
    /*
    id          coment
    ----------- --------------------------------------
    1000        coment1/coment2
    10001       comment1/comment2/comment3
    */
    drop function f_str
    drop table t_test