SQL Server CTE and recursion example

后端 未结 4 1003
臣服心动
臣服心动 2020-11-22 07:03

I never use CTE with recursion. I was just reading an article on it. This article shows employee info with the help of Sql server CTE and recursion. It is basically showing

4条回答
  •  清酒与你
    2020-11-22 07:42

    Would like to outline a brief semantic parallel to an already correct answer.

    In 'simple' terms, a recursive CTE can be semantically defined as the following parts:

    1: The CTE query. Also known as ANCHOR.

    2: The recursive CTE query on the CTE in (1) with UNION ALL (or UNION or EXCEPT or INTERSECT) so the ultimate result is accordingly returned.

    3: The corner/termination condition. Which is by default when there are no more rows/tuples returned by the recursive query.

    A short example that will make the picture clear:

    ;WITH SupplierChain_CTE(supplier_id, supplier_name, supplies_to, level)
    AS
    (
    SELECT S.supplier_id, S.supplier_name, S.supplies_to, 0 as level
    FROM Supplier S
    WHERE supplies_to = -1    -- Return the roots where a supplier supplies to no other supplier directly
    
    UNION ALL
    
    -- The recursive CTE query on the SupplierChain_CTE
    SELECT S.supplier_id, S.supplier_name, S.supplies_to, level + 1
    FROM Supplier S
    INNER JOIN SupplierChain_CTE SC
    ON S.supplies_to = SC.supplier_id
    )
    -- Use the CTE to get all suppliers in a supply chain with levels
    SELECT * FROM SupplierChain_CTE
    

    Explanation: The first CTE query returns the base suppliers (like leaves) who do not supply to any other supplier directly (-1)

    The recursive query in the first iteration gets all the suppliers who supply to the suppliers returned by the ANCHOR. This process continues till the condition returns tuples.

    UNION ALL returns all the tuples over the total recursive calls.

    Another good example can be found here.

    PS: For a recursive CTE to work, the relations must have a hierarchical (recursive) condition to work on. Ex: elementId = elementParentId.. you get the point.

提交回复
热议问题