产品表产品id  产品名称  产品主单位
1        香蕉        个
2        苹果        斤
3        橘子        斤产品单位表
产品单位id   产品单位名称  产品id
1                 斤         1
2                 箱         1
3                 支         1
4                 个         2
5                 箱         2
怎样得到
产品id   产品名称  产品单位
1        香蕉       个|斤|箱|支
2        苹果       斤|个|箱
3        橘子       斤可能一种产品就一个主单位,没有其他单位,像橘子,只有主单位斤,没有别的单位

解决方案 »

  1.   

    create function fun_test(@id int)
    return varchar(100)
    as
    begin
     declare @temp varchar(100)
     set @temp == ''
     select @temp = @temp + 产品单位名称 from  产品单位表 where 产品单位id=@id
     return @temp
    endselect A.产品id,fun_test(A.产品id)
    from 产品表 A,产品单位表 B
    where A.产品id=B.产品单位id
    group by A.产品id
      

  2.   

    use Tempdb
    go
    --> --> 
     
    if not object_id(N'Tempdb..#产品表') is null
    drop table #产品表
    Go
    Create table #产品表([产品id] int,[产品名称] nvarchar(2),[产品主单位] nvarchar(1))
    Insert #产品表
    select 1,N'香蕉',N'个' union all
    select 2,N'苹果',N'斤' union all
    select 3,N'橘子',N'斤'
    Goif not object_id(N'Tempdb..#产品单位表') is null
    drop table #产品单位表
    Go
    Create table #产品单位表([产品单位id] int,[产品单位名称] nvarchar(1),[产品id] int)
    Insert #产品单位表
    select 1,N'斤',1 union all
    select 2,N'箱',1 union all
    select 3,N'支',1 union all
    select 4,N'个',2 union all
    select 5,N'箱',2 union ALL
    select 5,N'斤',3
    Go
    Select *,
    [产品单位]=STUFF((SELECT '| '+[产品单位名称] FROM #产品单位表 WHERE [产品id]=a.[产品id] FOR XML PATH('')) ,1,1,'')
    from #产品表 AS a 
    /*
    产品id 产品名称 产品主单位 产品单位
    1 香蕉 个  斤| 箱| 支
    2 苹果 斤  个| 箱
    3 橘子 斤  斤
    */