--bom中重复引用到该产品相同版本   20150129增加    注意
---bom中重复引用到该产品不同版本   20150129增加     注意
加入此部份后计算相同的产品带版本号的单价有些问题,  麻烦帮忙解决.if object_id('GetBom','TF') is not null
    drop function GetBom
go
 
create function GetBom()
returns @tb table(MGoodsId Varchar(10), MQty int, BomVer Varchar(10), ItemNo int, GoodsId Varchar(10), Qty int, BomIdName Varchar(10), Price int, AM int) 
AS
begin
    declare @i int
    set @i = 1
    declare @t table(id int,BillId int, MGoodsId Varchar(10), MQty int, BomVer Varchar(10), ItemNo int, GoodsId Varchar(10), Qty int, BomId int, BomIdName Varchar(10), Price int, AM int, LevelId int)
 
    insert @t 
    select a.BillId,a.BillId,a.GoodsId, a.Qty, a.BomVer, b.ItemNo, b.GoodsId, b.Qty, b.BomId, c.BOMVER AS BomIdName, d.Price, b.Qty*d.Price AS AM, @i 
    from M_BOM a 
        join M_BOMD b ON a.BillId = b.BillId 
        left join M_BOM c ON b.BomId = c.BillId
        join GOODS d ON b.GoodsId = d.GoodsId
 
    while @i <= 10 AND @@RowCount <> 0
    begin
        set @i = @i + 1
 
        insert @t
        select a.Id,b.BillId, a.BomIdName, a.Qty, a.BomIdName, b.ItemNo, b.GoodsId, b.Qty, b.BomId, c.BOMVER AS BomIdName, d.Price, b.Qty*d.Price AS AM, @i 
        from @t a 
            join M_BOMD b ON a.BomId = b.BillId 
            left join M_BOM c ON b.BomId = c.BillId
            join GOODS d ON b.GoodsId = d.GoodsId
        where a.BomIdName IS NOT NULL AND a.LevelId = @i-1
    end
 
    select @i = max(levelid) from @t
    while @i >= 2
    begin
        update a set a.price = b.total, a.AM = a.Qty*b.total from @t a join (select id,BillId, sum(Qty*Price) as total from @t where levelid = @i group by id,BillId) b on a.BomId = b.BillId and a.id = b.id where a.levelid = @i-1
 
        set @i = @i - 1
    end
 
    insert @tb(MGoodsId, MQty, BomVer, ItemNo, GoodsId, Qty, BomIdName, Price, AM)
    select MGoodsId, MQty, BomVer, ItemNo, GoodsId, Qty, BomIdName, Price, AM 
    from @t 
    where levelid = 1 
    order by billid, itemno
 
    return
end
go
 
select * from dbo.getbom() where mgoodsid = 'x'
 
/*
MGoodsId   MQty        BomVer     ItemNo      GoodsId    Qty         BomIdName  Price       AM
---------- ----------- ---------- ----------- ---------- ----------- ---------- ----------- -----------
X          1           XXX        1           A          1           A          4           4
X          1           XXX        2           A          2           A2         5           10
 
(2 行受影响)
*/