2列列表 - 递归值替换 - SQL Server 2016

时间:2017-08-08 18:58:59

标签: sql sql-server recursion

我有很多产品已被淘汰并被其他产品取代。该表有2列:OriginalItem,SubstituteItem。

我想创建一个列表来保留OriginalItem,但用最近的替换替换SubtituteItem。因此,如果SubstitueItem位于OriginalItem列中,它将被替换。这可能发生1次或20次,这是我遇到困难的部分。

示例 - 原始列表

car1, car2    
car2, car3    
car3, car4

预期结果

car1, car4    
car2, car4    
car3, car4

感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

您可以使用recursive CTE执行此操作。像下面这样的东西可以让你进入球场:

WITH recCTE AS
(
    --recursive seed (Starting point) which will be every record in this case
    SELECT
        originalitem,
        substituteitem,
        1 as depth --track how many iterations
        CAST(originalitem + '>' + substituteitem AS NVARCHAR(500)) as path --track the full path from original item to substitute for fun
    FROM yourtable

    UNION ALL

    --recursive term (gets called over and over again until the join fails)
    SELECT
        recCTE.originalItem,
        yourtable.substituteitem,
        recCTE.depth + 1, --increment depth
        recCTE.path + ">" + yourtable.substituteitem --add to the path
    FROM
        recCTE  --this CTE provides the foundation for this statement because it's recursive
        INNER JOIN youttable ON
            recCTE.substituteitem = yourtable.originalitem --joining sub to orig
    WHERE depth < 20 --just in case of cycling
)
SELECT * FROM reccCTE;