用友U9ERP BOM展开SQL脚本
本帖最后由 hechunhuicom 于 2016-12-28 16:55 编辑
declare @maincode char(60)
set @maincode='10.1210.0012'--产成品品号
declare @i int
set @i=0
--SELECT MD003 FROM #BOMMD WHERE MD001='CG.16120509001.00909'
select item.ID MID,item.Code MD001,item.Name MName,itemlin.ID ZID,itemlin.Code MD003,itemlin.Name ZName,
Convert(decimal(18,3),B.UsageQty) UsageQty --用量
,Convert(decimal(18,3),B.ParentQty) ParentQty --母件底数
,Convert(decimal(18,3),Convert(decimal(18,3),B.UsageQty)/Convert(decimal(18,3),B.ParentQty)) MD006 --计算实际用量
INTO #BOMMD
from CBO_BOMMaster as A
inner join CBO_BOMComponent as B on A.ID = B.BOMMaster
left join CBO_ItemMaster item on A.ItemMaster=item.ID
left join CBO_ItemMaster itemlin on B.ItemMaster=itemlin.ID
where
A.BOMType=0 --0 为自制件 1为委外
and A.AlternateType=0 --0 生产目的为主制造 1 为委外
and A.BOMType=0 --0 BOM类型为自制 1为委外 10.0115.0006
and
A.Org=1002011047606283
and A.DisableDate > GETDATE() --失效日期需大于今天日期
--and A.ID in(select max(ID)
--from CBO_BOMMaster where Org='1002011047606283'
--group by BOMVersionCode,ItemMaster,Project
--having max(DisableDate) > GETDATE() )
--AND A.ItemMaster = (select id from CBO_ItemMaster where Code =('10.5001.0010') and Org='1002011047606283')
--MD001为主件品号,MD003为元件品号,两者形成对应关系
--定义主件品号临时表
declare @tmp_main table (品号 CHAR(60))
--将待查品号存入主件品号临时表
INSERT INTO @tmp_main SELECT MD003 FROM #BOMMD WHERE MD001=@maincode
--定义BOM明细临时表
declare @tmp_bom table (主件品号 char(60),元件品号 char(60),组成用量 float,阶数 int)
--将待查品号下一级元件品号数据存入BOM明细临时表
insert into @tmp_bom select MD001,MD003,MD006,@i from #BOMMD
where MD001 =@maincode
--如果BOMM表MD001(主件品号)存在于BOM明细临时表中的元件品号且阶数为当前最低层,进入循环
while exists(select * from #BOMMD where MD001 in (select 元件品号 from @tmp_bom where 阶数=@i))
begin
--向BOM明细临时表插入BOMMD中MD001与主件品号临时表品号一致的数据(以主件品号临时表左关联BOMMD,存在多对一关系)
insert into @tmp_bom select MD001,MD003,MD006,@i+1 from
(select MD001,MD003,MD006 from @tmp_main LEFT join #BOMMD on 品号=MD001
)A where MD001 is not null
--清空主件品号临时表
delete from @tmp_main
--向主件品号临时表插入BOMMD中的主品号存在于BOM明细临时表元件品号的MD003(子品号)
INSERT INTO @tmp_main SELECT MD003 FROM #BOMMD WHERE MD001
in (select 元件品号 from @tmp_bom where 阶数=@i)
set @i=@i+1
end
select * from @tmp_bom ORDER BY 阶数,元件品号
drop table #BOMMD