表 aaId aName
001  洗衣粉
002  香皂
003  牙刷
004  土豆片
.....表 b
bName    bCode
家庭用品  001,002
食物      004求得到家庭用品  洗衣粉,肥皂
食物      土豆片表b的bCode用,号分割,也许有一项,也许有很多项,其实匹配表a的ID值.

解决方案 »

  1.   

    select bname,replace(bcode,aid,aname) from a,b
      

  2.   


    不好意思。楼主。刚才随手敲了下就出去了。。
    create table ta (aid varchar(50),aname varchar(50))
    insert into ta select '001','洗衣粉'
    insert into ta select '002','香皂'
    insert into ta select '003','牙刷'
    insert into ta select '004','土豆片'
    create table tb (bname varchar(50),bcode varchar(50))
    insert into tb select '家庭用品','001,002'
    insert into tb select '食物','004'create function wspdd(@bcode varchar(50))
    returns varchar(500)
    as
    begin
    declare @sql varchar(500)
    select @sql=isnull(@sql+',','')+aname from ta where charindex(aid,@bcode)>0
    return @sql
    end
    select bname,dbo.wspdd(bcode) from tb
      

  3.   

    --参考
    tba
    ID  classid   name
    1     1,2,3   西服 
    2     2,3    中山装
    3     1,3    名裤
    tbb 
    id   classname
    1     衣服
    2     上衣
    3     裤子我得的结果是
    id   classname            name
    1     衣服,上衣,裤子      西服 
    2          上衣,裤子     中山装
    3     衣服,裤子          名裤create table tba(ID int,classid varchar(20),name varchar(10))
    insert into tba values(1,'1,2,3','西服')
    insert into tba values(2,'2,3'  ,'中山装')
    insert into tba values(3,'1,3'  ,'名裤')
    create table tbb(ID varchar(10), classname varchar(10))
    insert into tbb values('1','衣服')
    insert into tbb values('2','上衣')
    insert into tbb values('3','裤子')
    go--第1种方法,创建函数来显示
    create function f_hb(@id varchar(10))
    returns varchar(1000)
    as
    begin
      declare @str varchar(1000)
      set @str=''
      select @str=@str+','+[classname] from tbb where charindex(','+cast(id as varchar)+',',','+@id+',')>0
      return stuff(@str,1,1,'')
    end
    go 
    select id,classid=dbo.f_hb(classid),name from tba
    drop function f_hb
    /*
    id          classid       name       
    ----------- ------------- ---------- 
    1           衣服,上衣,裤子 西服
    2           上衣,裤子      中山装
    3           衣服,裤子      名裤
    (所影响的行数为 3 行)
    */--第2种方法.update
    while(exists (select * from tba,tbb where charindex(tbb.id,tba.classid) >0))
    update tba
    set classid= replace(classid,tbb.id,tbb.classname)
    from tbb
    where charindex(tbb.id,tba.classid)>0
    select * from tba
    /*
    ID          classid              name       
    ----------- -------------------- ---------- 
    1           衣服,上衣,裤子       西服
    2           上衣,裤子            中山装
    3           衣服,裤子            名裤
    (所影响的行数为 3 行)
    */
    drop table tba,tbb