父级和子级递归逻辑-MS Sql

问题描述 投票:0回答:1

需要以下代码的帮助。

DECLARE @BomStructure TABLE(ParentPart Varchar(50), Component Varchar(50))  -- Parent & Child

INSERT @BomStructure  VALUES( 'P01-1000W', 'P01-1000WX');
INSERT @BomStructure  VALUES( 'P01-1000W', 'PKG-INSERT1000' );
INSERT @BomStructure  VALUES('P01-1000W',   'PKG-HANG CARD-XL' );
INSERT @BomStructure  VALUES( 'P01-1000W',  'PKG-BAG10' );
INSERT @BomStructure  VALUES( 'P01-1000W',  'PKG-BAG16');
INSERT @BomStructure  VALUES( 'P01-1000W',  'BOX RSC-01');
INSERT @BomStructure  VALUES( 'P01-1000W',  'F92-0306');
INSERT @BomStructure  VALUES('P01-1000WX',  'P01-1000W-TOP');
INSERT @BomStructure  VALUES('P01-1000WX',  'P01-1000W-BACK');
INSERT @BomStructure  VALUES('P01-1000WX',  'P01-1000W-BOTTOM');
INSERT @BomStructure  VALUES('P01-1000W-TOP', 'P12-5060WHA96');
INSERT @BomStructure  VALUES('P01-1000W-BACK','P12-5060WHA96');
INSERT @BomStructure  VALUES('P01-1000W-BOTTOM','P12-5060WHA96');
INSERT @BomStructure  VALUES('PKG-INSERT1000',  'LABOR-KIT');


  ;WITH Relation AS (
  SELECT ParentPart, Component
  , 0 AS Level
  , CAST(Component AS VARCHAR(255)) AS Path
  FROM @BomStructure 
  UNION ALL
  SELECT i.ParentPart, i.Component
  , Level + 1
  ,CAST(Path + '/' + CAST(i.Component AS VARCHAR(255)) AS VARCHAR(255)) AS Path
  FROM @BomStructure i 
  INNER JOIN Relation RL ON RL.ParentPart = i.Component)
SELECT * FROM Relation where ParentPart ='P01-1000W' ORDER BY Level, Component

我通过这段代码得到的输出如下

ParentPart  Component   Level   Path
P01-1000W   BOX RSC-01  0   BOX RSC-01
P01-1000W   F92-0306    0   F92-0306
P01-1000W   P01-1000WX  0   P01-1000WX
P01-1000W   PKG-BAG10   0   PKG-BAG10
P01-1000W   PKG-BAG16   0   PKG-BAG16
P01-1000W   PKG-HANG CARD-XL    0   PKG-HANG CARD-XL
P01-1000W   PKG-INSERT1000  0   PKG-INSERT1000
P01-1000W   P01-1000WX  1   P01-1000W-BOTTOM/P01-1000WX
P01-1000W   P01-1000WX  1   P01-1000W-BACK/P01-1000WX
P01-1000W   P01-1000WX  1   P01-1000W-TOP/P01-1000WX
P01-1000W   PKG-INSERT1000  1   LABOR-KIT/PKG-INSERT1000
P01-1000W   P01-1000WX  2   P12-5060WHA96/P01-1000W-BOTTOM/P01-1000WX
P01-1000W   P01-1000WX  2   P12-5060WHA96/P01-1000W-BACK/P01-1000WX
P01-1000W   P01-1000WX  2   P12-5060WHA96/P01-1000W-TOP/P01-1000WX

对于具有2级或更高级别结构的任何ParentPart,我想查看路径的直接父级

例如,请参见下面的期望输出

enter image description here

非常感谢您的帮助。谢谢!

mysql loops sql-server-2008 recursion common-table-expression
1个回答
0
投票

仅不要构建路径,而是存储您以其开头的组件

 ;WITH Relation AS (
  SELECT ParentPart, Component
  , 0 AS Level
  ,Component as start_component AS Path
  FROM @BomStructure 
  UNION ALL
  SELECT i.ParentPart, i.Component
  , Level + 1
  ,RL.startComponent
  FROM @BomStructure i 
  INNER JOIN Relation RL ON RL.ParentPart = i.Component)
© www.soinside.com 2019 - 2024. All rights reserved.