日期:2014-05-18  浏览次数:20608 次

求各位大哥帮我看看这个语句怎么弄
现在有一个产品表   BOM如下:
  产品编码       组件编码  
  3000                 2000
  3000                 1000
  3000                 2100
  。。。             。。。
  2000                 1200
  2000                 1300
  。。。               。。。
  2100                 1300
  2100                 1500
。。。             。。。。
  3200                 1100
  3200                 1230
  3200                 2200
  2200                 1340
  2200                 1370

也就是产品3000   由2000,1000,2100组成,其中2000又由1200,1300组成,2100由1300,1500组成。。可能有很多层的   。2开头可能是叶子   也可能不是
现在希望得到3000的最低层的所有组成,也就是叶
即得到以下结果:
    产品       叶组件
    3000       1000
    3000       1200
    3000       1300
    3000       1500    
    。。。   。。。
    3200       1100
    3200       1230
    3200       1340
    3200       1370
。。。。。。
也就是   我需要显示BOM表里面所有的产品按上面那样显示出来
请各位大哥们帮一下忙,谢谢大家


------解决方案--------------------
create table BOM(PID int,ID int)
insert into BOM select 3000,2000
insert into BOM select 3000,1000
insert into BOM select 3000,2100
insert into BOM select 2000,1200
insert into BOM select 2000,1300
insert into BOM select 2100,1300
insert into BOM select 2100,1500

insert into BOM select 3200,2000
insert into BOM select 3200,1000
insert into BOM select 3200,1400
go

create function f_getChild()
returns @t table(PID int,ID int)
as
begin
declare @t1 table(PID int,MID int,ID int)

insert into @t1(PID,MID,ID)
select
t.PID,t.PID,t.ID
from
BOM t
where
not exists(select 1 from BOM where ID=t.PID)

while @@rowcount <> 0
begin
insert into @t1(PID,MID,ID)
select
b.PID,a.PID,a.ID
from
BOM a,
@t1 b
where
a.PID=b.ID
and
not exists(select 1 from @t1 where MID=a.PID)
end

insert into @t (PID,ID)
select
distinct PID,ID
from
@t1 t
where
not exists (select 1 from @t1 where MID=t.ID)

return
end
go

select * from dbo.f_getChild()
go

/*
PID ID
----------- -----------
3000 1000
3000 1200
3000 1300
3000 1500
3200