依样做一个UDF吧:
----------------------------------------------------------------------------
--生成测试数据
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

解决方案 »

  1.   

    create function f_str(@name varchar(20))
    returns varchar(8000)
    as
    begin
          declare @str varchar(8000)
          set @str=''
          select @str=@str+'/'+[str] from 表 where name=@name
          return stuff(@str,1,1,'')
    end
    go--查询
    select identity(int,1,1) id
           ,name
           ,dbo.f_str(name) as 'name'
    into #
    from 表
    group by nameselect * from #
      

  2.   

    --创建用户定义函数
    create function f_str(@name varchar(20))
    returns varchar(8000)
    as
    begin
        declare @ret varchar(8000)
        set @ret = ''
        select @ret = @ret+'/'+str from 表 where name = @name 
        set @ret = stuff(@ret,1,1,'')
        return @ret 
    end
    go
    --生成数据
    select 
        identity(int,1,1) as id,
        name,
        str=dbo.f_str(str) 
    into 
        #T
    from
        表 
    group by 
        name 
    order by 
        name--查看结果
    select * from #T--删除测试数据
    drop table #T
    drop function f_str
    go
      

  3.   

    alter function f_test(@Name varchar(10))
    returns varchar(1000)
    as
    Begin
    declare @return varchar(1000)
    set @return = ''
    select @return= '/'+str+@return from tb where Name=@Name
    set @return = stuff(@Return ,1,1,'')
    return @return
    Endselect name ,dbo.f_test(name) from tb group by name
      

  4.   

    --我也练习一遍
    --函数
    Create Function F_GetStr(@name varchar(10))
    returns varchar(200)
    as 
    begin
       declare @return varchar(200)
       set @return=''
       select @return=@ruturn+'/'+str from 表 where name=@name
       set @return=stuff(@return,1,1,'')
    end--分组查询
    select name,
           str=dbo.F_GetStr(name)
    from 表
    Group by Name