SQL递归查询(with cte as) 物料分解

编程入门 行业动态 更新时间:2024-10-25 12:21:49

SQL<a href=https://www.elefans.com/category/jswz/34/1771140.html style=递归查询(with cte as) 物料分解"/>

SQL递归查询(with cte as) 物料分解

需求

最近在做一个MRP的项目,需要根据生产下达的计划从原始无聊表中分解出成品所需要的原材料和数量.

参考

.html

.html

代码实现

SQL数据表结构

CREATE TABLE [dbo].[cProduction]([ID] [int] IDENTITY(1,1) NOT NULL,[Production] [varchar](max) NULL,[MaterialNo] [varchar](100) NULL,[CompQuan] [float] NULL
) ON [PRIMARY]GO
View Code
INSERT INTO cProduction VALUES('JCV3311149605','A5E01194561',1)
INSERT INTO cProduction VALUES('JCV3311149605','JCV2511141838',1)
INSERT INTO cProduction VALUES('JCV3311149605','JCV2511141929',1)
INSERT INTO cProduction VALUES('JCV2511141838','JCV3311800707',1)
INSERT INTO cProduction VALUES('JCV3311800707','JCVRM00040003',1)
INSERT INTO cProduction VALUES('JCV3311800707','JCVRM00040004',1)
View Code

SQL代码实现

假设对产品JCV3311149605下达的计划为1000

with cte as(
select [Production],[MaterialNo],[CompQuan]*1000 as quan,1 as lvl,path=CAST(CompQuan AS INT) from cProduction where Production = 'JCV3311149605' 
union all 
select d.[Production],d.[MaterialNo],C.path*d.[CompQuan]*1000 as quan,lvl+1,path=CAST(D.CompQuan*c.path AS int)  from cte c inner join cProduction d on c.materialno = d.Production
) select * from cte OPTION(MAXRECURSION 0) 
View Code

效果如下,结果正确:

转载于:.html

更多推荐

SQL递归查询(with cte as) 物料分解

本文发布于:2023-06-27 08:24:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/908738.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   物料   分解   SQL   cte

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!