---创建临时表,插入测试数据--
create table #bom(母件 varchar(50),子件项次 varchar(100),子件 varchar (50),用量 numeric(16,4))
insert into #bom
select '10210100030','1','20012100008',1 union all
select '10210100030','2','20012110008',0.5 union all
select '10210100030','3','30300701001',1 union all
select '20012100008','1','2001210P161',1 union all
select '20012100008','2','30400201100',2 union all
select '20012110008','1','2001211S104',1 union all
select '20012110008','2','30400203000',0.5 union all
select '10210100026','1','20012100005',3 union all
select '10210100026','2','20012190012',4 union all
select '10210100026','3','30300201001',1 union all
select '20012100005','1','2001210P162',1 union all
select '20012100005','2','30400201100',0.5 union all
select '20012190012','1','2001219Z001',2 union all
select '2001219Z002','1','30400201111',2 union all
select '20012190012','2','2001219Z002',2
--drop table #bom
--select * from #bom
---创建可多选函数---
create function SplitIn(@c varchar(2000),@split varchar(2))
returns @t table(col varchar(32))
as
begin
while(charindex(@split,@c)<>0)
begin
insert @t(col) values (substring(@c,1,charindex(@split,@c)-1))
set @c = stuff(@c,1,charindex(@split,@c),'')
end
insert @t(col) values (@c)
return
end
----创建展BOM存储过程---
create proc [dbo].[p_bom] @mmaster varchar(50)
as
begin
-----变量表--------
declare @BOM table (序号 varchar(100),阶次 varchar(10),层级 varchar(100),母件 varchar(50),子件 varchar(50),用量 numeric(16,4),实际用量 numeric(16,4))
;
----递规运算BOM结构,结果插入表变量@BOM-----
with t
As
(
select le=convert(varchar(10),1),convert(varchar(100),子件项次) as 层级,*,实际用量=cast (用量 as numeric(16,4))
from #bom
Where 母件 in (select col as 母件 from splitIn(@mmaster,','))
union all
select le=convert(varchar(10),le+1),
convert(Varchar(100),层级+','+convert(Varchar(100),B.子件项次)) As 层级, ---BOM子件项次合并,体现层级,用于排序体现BOM结构
B.*,
cast(t.实际用量*b.用量 as numeric(16,4)) AS 实际用量
from T
inner join #bom B on T.子件=B.母件
)
insert into @BOM select ROW_NUMBER() over(order by 层级) 序号,*
from
(
Select REPLICATE('.',le)+LTRIM(le)as 阶次 ,---树状
层级,母件,子件,用量,实际用量
From t
union all
select distinct 阶次= '0','0' as 层级,'' as 母件,母件 as 子件,用量=0,实际用量=0 ---顶层母件
from #bom as a
where a.母件 in (select col As 母件 from splitIn(@mmaster,','))
)c
order by c.层级
select * from @bom
end
GO
exec p_bom'10210100030,10210100026'