数据:
Table1:id C1
-----------
1 cc
2 cdTable2:id TypeIndex
-----------------
1 1
1 2
1 3Table3:
TypeIndex Type
-----------------------
1 a
2 b
3 c
4 d要求获得如下数据:id C1 StrType
------------------------
1 cc a;b;c
2 cd null有正解即结贴。请牛人帮忙

解决方案 »

  1.   

    create function f_union(@id int)
    returns varchar(100)
    as
    begin
     
      declare @sql varchar(100)
      set @sql=''
     if exists(select 1 from table2 where id=@id)
      begin
         select @sql=@sql+';'+b.type from table2 a,table3 b 
         where a.typeindex=b.typeindex and a.id=@id order by a.typeindex
         return(stuff(@sql,1,1,''))
      end
    else
      return ''
    end
    goselect id,c1,StrType=dbo.f_union(id)  from table1