DB for z/OS 中的递归查询

问题描述

亲爱的,我有一个名为“PROGRAM”的源表,如下所示

Program CSECT
X       Y
B       X
M       P
A       L
B       D
C       D
A       C
B       C
A       B
D       B

给定一个程序,例如“A”,我需要找到所有关联的 CSECT

Program CSECT
A       L
A       C
A       B
B       D
B       X
X       Y

我尝试过如下递归查询,但它循环引用示例 B-D 和 D-B

WITH RPL (Program,Csect) AS
      (SELECT ROOT.Program,ROOT.Csect
         FROM Program ROOT
         WHERE Program = 'A'
      UNION ALL
         SELECT CHILD.Program,CHILD.Csect
            FROM RPL PARENT,Program CHILD
            WHERE PARENT.Csect = CHILD.Program)
 SELECT *
     FROM RPL;

解决方法

您可以添加额外的列(链),其中包含当前行的完整路径,如下所示。如果 CHILD.Program 已包含在此类路径中,则不应添加新行。

WITH RPL (Program,Csect,Chain) AS
(
SELECT ROOT.Program,ROOT.Csect,CAST('|' || ROOT.Program || '|' AS VARCHAR(1000))
FROM Program ROOT
WHERE Program = 'A'
    UNION ALL
SELECT CHILD.Program,CHILD.Csect,PARENT.Chain || CHILD.Program || '|' 
FROM RPL PARENT,Program CHILD
WHERE PARENT.Csect = CHILD.Program
    AND LOCATE('|' || CHILD.Program || '|',PARENT.Chain) = 0
)
SELECT DISTINCT Program,Csect
FROM RPL
ORDER BY Program;