例如:
表user
userid       name
1            张三
2            李四表product
id  userid   product
1    1        基金
2    1        股票
3    2        基金
我要查询所有用户,但是也要显示产品信息,如下:
1     张三     基金,股票
2     李四     基金应该写一个自定义函数,请教该怎么写,谢谢大家!

解决方案 »

  1.   

    --带符号合并行列转换--有表t,其数据如下:
      a b
      1 1
      1 2
      1 3
      2 1
      2 2
      3 1
    --如何转换成如下结果:
      a b
      1 1,2,3
      2 1,2
      3 1 create table tb
    (
       a int,
       b int
    )
    insert into tb(a,b) values(1,1)
    insert into tb(a,b) values(1,2)
    insert into tb(a,b) values(1,3)
    insert into tb(a,b) values(2,1)
    insert into tb(a,b) values(2,2)
    insert into tb(a,b) values(3,1)
    goif object_id('pubs..f_hb') is not null
       drop function f_hb
    go--创建一个合并的函数
    create function f_hb(@a int)
    returns varchar(8000)
    as
    begin
      declare @str varchar(8000)
      set @str = ''
      select @str = @str + ',' + cast(b as varchar) from tb where a = @a 
      set @str = right(@str , len(@str) - 1)
      return(@str)
    End
    go--调用自定义函数得到结果:
    select distinct a ,dbo.f_hb(a) as b from tbdrop table tb--结果
    a           b     
    ----------- ------
    1           1,2,3
    2           1,2
    3           1(所影响的行数为 3 行)
      

  2.   

    create table tba (userid int,name varchar(10))
    insert into tba values(1,                         '张三') 
    insert into tba values(2,                         '李四')
    create table tbb (id int,userid int,product varchar(10))
    insert into tbb values(1,         1,                 '基金') 
    insert into tbb values(2,         1,                 '股票') 
    insert into tbb values(3,         2,                 '基金') 
    go
    --创建一个合并的函数
    create function f_hb(@userid int)
    returns varchar(8000)
    as
    begin
      declare @str varchar(8000)
      set @str = ''
      select @str = @str + ',' + cast(product as varchar) from tbb where userid = @userid
      set @str = right(@str , len(@str) - 1)
      return(@str)
    End
    go--调用自定义函数得到结果:
    select tba.*,t.product from tba,
    (select distinct userid ,dbo.f_hb(userid) as product from tbb) t
    where tba.userid = t.useriddrop table tba,tbb
    drop function f_hb/*
    userid      name       product    
    ----------- ---------- -----------
    1           张三         基金,股票
    2           李四         基金(所影响的行数为 2 行)
    */
      

  3.   


    表user 
    userid               name 
    1                         张三 
    2                         李四 表product 
    id     userid       product 
    1         1                 基金 
    2         1                 股票 
    3         2                 基金 
    ----------------------------
    create function wsp(@userid int)
    returns varchar(8000)
    as
    begin
      declare @str varchar(8000)
      select @str = isnull(@str + ',','') + product from product where userid = @userid 
      return(@str)
    End调用函数:select name,dbo.wsp(userid) from user