有2个表
表1                     表2
id name                 表1.id    info
1  w                       1      ttt
2  e                       1      rrr表1和表2关联,请问怎么样用查询语句可以查询出这样的结果:
表1.name     表2.info
w            ttt,rrr谢谢!

解决方案 »

  1.   

    create function f_union(@id int)
    returns varchar(100)
    as
    begin
      declare @sql varchar(100)
      set @sql=''
      select @sql=@sql+','+info from 表2 where id=@id 
      return(stuff(@sql,1,1,''))
    end
    goselect [name],info=dbo.f_union(id) from 表1,表2 
    where 表1.id=表2.id group by 表2.id
      

  2.   

    create table tb(ID int,NAME varchar(10))
    insert into tb 
    select 1,'w' union all
    select 2,'e' 
    gocreate table tt(ID int,inf varchar(10))
    insert into tt
    select 1,'ttt' union all
    select 1,'rrr' 
    gocreate function dbo.fc_str(@id varchar(100))
    returns varchar(100)
    as
    begin
     declare @sql varchar(1000)
     set @sql=''
     select @sql=@sql+','+cast(inf as varchar(100)) from tt where id=@id
     return stuff(@sql,1,1,'')
    end
    goselect a.name,dbo.fc_str(b.id) as inf from tb a,tt b where a.id=b.id group by b.id,a.name