0

我正在尝试识别我需要递归 cte 的数据中的递归/循环引用。

例如,我有一个包含Product_IDand的表Inner_Product_ID。当 Product_ID A 在 Product_ID B 内部时,我想要结果,它在 Product_ID C 内部,在 Product_ID A 内部。

样本数据

PRODUCT_ID    INNER_PRODUCT_ID
   12              36
   24              12
   36              24
   1               2
   3               4

预期产出

PRODUCT_ID    INNER_PRODUCT_ID
   12              36
   24              12
   36              24

我已尝试使用 cte 进行基本查询,但不确定如何针对此问题实现递归 cte:

;WITH RNCTE
AS (   SELECT *,
           ROW_NUMBER() OVER (PARTITION BY pr1.PRODUCT_ID
                              ORDER BY pr1.PRODUCT_ID
                             ) rn
       FROM
           TableName pr1),
      cte
AS (   SELECT *
       FROM RNCTE
       WHERE RNCTE.rn = 1
       UNION ALL
       SELECT *
       FROM cte   c
           JOIN RNCTE r
                   ON r.PRODUCT_ID = c.PRODUCT_ID
                      AND r.rn = c.rn + 1)
SELECT *
FROM  cte;
4

2 回答 2

1

试试这个 - 它遍历链接的记录,并确定“walk”是否最终终止。如果它持续的时间超过了表中的记录数,那么它一定是一个循环。“有效”我不确定!

;WITH UCNT AS (SELECT count(0) c from products),
        RNCTE 
    AS (SELECT 1 as Levle, Product_ID, INNER_PRODUCT_ID FROM Products
        UNION ALL
        SELECT levle + 1, P.Product_ID, P.INNER_PRODUCT_ID
                     FROM RNCTE R 
                        JOIN Products P 
                            ON P.PRODUCT_ID = R.INNER_PRODUCT_ID
        WHERE levle <= (SELECT c + 2 FROM UCNT))
        --when the recursion count levle exceeds the count of records in the table, 
        --we must have recursion, because 
        --termination has to otherwise occur.  The most extreme case is 
        --that all records are linked, with termination
        --after this, we have to be in a 'loop' 
        SELECT TOP 1 with ties * FROM RNCTE order by levle desc
        option (maxrecursion 0)
于 2018-11-29T16:46:50.127 回答
0

我认为您不需要使用CTERECUSRIVE CTE

SELECT pr1.*
FROM TableName pr1
WHERE EXISTS (SELECT 1 FROM TableName pr2 WHERE pr2.INNER_PRODUCT_ID = pr1.PRODUCT_ID);
于 2018-11-29T16:15:40.007 回答