SQL Server: How to limit CTE recursion to rows just recursivly added?

前端 未结 8 1122
北海茫月
北海茫月 2020-12-08 23:12

Simpler Example

Let\'s try a simpler example, so people can wrap their heads around the concepts, and have a practical example that you can copy&paste into SQL

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 23:31

    Well, your answer is not quite that obvious :-)

    WITH (NodeChildren) AS
    {
       --initialization
       SELECT ParentNodeID, ChildNodeID, 1 AS GenerationsRemoved
       FROM Nodes
    

    This part is called the "anchor" part of the recursive CTE - but it should really only select one or a select few rows from your table - this selects everything!

    I guess what you're missing here is simply a suitable WHERE clause:

    WITH (NodeChildren) AS
    {
       --initialization
       SELECT ParentNodeID, ChildNodeID, 1 AS GenerationsRemoved
       FROM Nodes
       **WHERE ParentNodeID IS NULL**
    

    However, I am afraid your requirement to have not just the "straight" hierarchy, but also the grandparent-child rows, might not be that easy to satisfy.... normally recursive CTE will only ever show one level and its direct subordinates (and that down the hierarchy, of course) - it doesn't usually skip one, two or even more levels.

    Hope this helps a bit.

    Marc

提交回复
热议问题