表A
id name
1 小明
2 小刚
3 小刘
4 小王表B
id class nameid
1 打篮球 1,2,3,
2 踢足球 2,3,4,
3 打兵乓球 1,3,4,
求出打篮球,踢足球,打兵乓球的人名,如下
1 打篮球   小明,小刚,小刘
2 踢足球   小刚,小刘,小王
3 打兵乓球 小明,小刘,小王

解决方案 »

  1.   

    写一个函数 根据id取得名称 
    然后
    select id,class,函数(nameid) from 表B 
      

  2.   

    create table t(id  int,  name varchar(10))
    insert into t 
     
    select 1, '小明'union all
    select 2, '小刚'union all
    select 3, '小刘'union all
    select 4, '小王'
    create table t1(id  int, class varchar(10),nameid  varchar(10))
    insert into t1 
    select 1, '打篮球','1,2,3' union all
    select 2, '踢足球','2,3,4' union all
    select 3, '打兵乓球','1,3,4'alter function tr_1(@name varchar(10))
    returns varchar(100)
    as
    begin
    declare @str varchar(100)
    select @str=isnull(@str,'')+','+name from t where charindex(cast(id as varchar(5)),@name)>0
    return stuff(@str,1,1,'')
    end 
    select id,class,dbo.tr_1(nameid) name from t1 
      

  3.   

    提醒一下,自定义函数的SELECT里应该加一个ORDER BY以保证生成的字符串顺序与原字符串顺序一致。
      

  4.   

    关键是把表B中的nameid分开来和表a对照就可以了。
      

  5.   

    --> --> (wufeng4552)生成測試數據
     
    if not object_id('ta') is null
    drop table ta
    Go
    Create table ta([id] int,[name] nvarchar(2))
    Insert ta
    select 1,N'小明' union all
    select 2,N'小刚' union all
    select 3,N'小刘' union all
    select 4,N'小王'
    Go
    if not object_id('tb') is null
    drop table tb
    Go
    Create table tb([id] int,[class] nvarchar(4),[nameid] nvarchar(6))
    Insert tb
    select 1,N'打篮球',N'1,2,3,' union all
    select 2,N'踢足球',N'2,3,4,' union all
    select 3,N'打兵乓球',N'1,3,4,'
    Go
    Select b.ID,
           b.[class],
           [nameid]=stuff((select ','+[name]
                           from ta a
                           where charindex(','+ltrim(a.id)+',',','+b.[nameid]+',')>0
                           for xml path('')),1,1,'')
    from tb b
    /*
    ID          class nameid
    ----------- ----- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    1           打篮球   小明,小刚,小刘
    2           踢足球   小刚,小刘,小王
    3           打兵乓球  小明,小刘,小王(3 個資料列受到影響)*/
      

  6.   

    这种问题,直接用Sql文写太复杂了,还是用函数或者用存储过程