Sql-server – CTE Running in Infinite Loop

ctesql server

My CTE runs in an infinite loop for a specific customer and I am not able to find out why.

Here is the query:

;WITH ClassTree
           AS (SELECT ID, NAME, Parent_ID
               FROM   TableName
               WHERE  ID = 1
               UNION ALL
               SELECT T.ID, T.NAME, T.Parent_ID
               FROM   TableName T WITH (NOLOCK)
                      JOIN ClassTree
                        ON Parent_ID = ClassTree.ID
)
SELECT * FROM ClassTree

Best Answer

I think this should find the problem record for you. It adds a LEVEL to your hierarchy, then looks for an individual ID record that exists at multiple levels.

;WITH ClassTree
           AS (SELECT ID, NAME, Parent_ID, 1 as 'Level'
               FROM   TableName
               WHERE  ID = 1
               UNION ALL
               SELECT T.ID, T.NAME, T.Parent_ID, Level + 1 as 'Level'
               FROM   TableName T WITH (NOLOCK)
                      JOIN ClassTree
                        ON Parent_ID = ClassTree.ID
)

SELECT *
FROM ClassTree c1
WHERE EXISTS (SELECT 1 FROM ClassTree c2
              WHERE c2.id = c1.id
              AND c2.Level > c1.level)