这是一张人员的角色分配表:UserID  RoleID   RoleName
 1        1       管理员
 1        2       操作员
 2        1       管理员
 2        2       操作员
 2        3       财务将人员拥有的角色用逗号分割显示: UserID   RoleName
 1        管理员,操作员
 2        管理员,操作员,财务
请教高手这个SQL如何写!!!

解决方案 »

  1.   

    --生成测试数据
    create table 表(UserID int,RoleID int,Rolename varchar(80))
    insert into 表 select 1,1,'管理员'
    insert into 表 select 1,2,'操作员'
    insert into 表 select 1,1,'管理员'
    insert into 表 select 2,2,'操作员'
    insert into 表 select 2,3,'财务'go--创建用户定义函数
    create function f_str(@Userid int)
    returns varchar(8000)
    as
    begin
        declare @ret varchar(8000)
        set @ret = ''
        select @ret = @ret+','+RoleName from 表 where Userid = @Userid
        set @ret = stuff(@ret,1,1,'')
        return @ret 
    end
    go
    --执行
    select Userid,人员=dbo.f_str(Userid) from 表 group by Userid order by Userid
    go
      

  2.   

    create function f_connect(@id int)
    returns varchar(200)
    as
      begin 
        declare @s_ret varchar(200)
        set @s_ret = ''
        select @s_ret = @s_ret + ',' + rolename from t_connect
        where userid = @id
        select @s_ret = stuff(@s_ret , 1 ,1 , '')
        return @s_ret
      end create table t_connect
    (
      userid int,
      roleid int,
      rolename varchar(20)
    )insert into t_connect
    select 1, 1, '管理员'  union
    select 1, 2, '操作员'  union
    select 2, 1, '管理员'  union
    select 2, 2, '操作员'  union
    select 2, 3, '财务'   
    select UserID ,dbo.f_connect(UserID) from t_connect
    group by UserID