How to Traverse All Foreign Keys to Generate All Possible Paths
I would try one or both of the following:


You've already added a Hops counter column in the anchor. In the recursive part of the CTE, you can filter WHERE cte2.Hops&lt;20
In the first cte common table expression, I would add WHERE fk.parent_object_id!=fk.referenced_object_id to exclude infinite self-referencing foreign keys (like parent-child hierarchies).