Recursive CTE in presence of circular references

╄→尐↘猪︶ㄣ 提交于 2019-11-29 16:17:19

You will need to put your WHERE-filter in the CTE part of your query, like so:

WITH recursive_cte (root_id, id) AS (
  SELECT parent_id, id
  FROM test_cte
  WHERE id=0       -- Restrict your recursion to start from the item with id = 0, instead of considdering all items.
  UNION ALL
  SELECT t.parent_id, r.id
  FROM test_cte t
  INNER JOIN recursive_cte r
  ON (r.root_id=t.id)
)
SELECT *
FROM recursive_cte

This may not be an elegant solution, but it seems to work. Store the list of visited ids in a list and exclude them from further searches. I think this is the right comparison for your query:

WITH recursive_cte(root_id, id, ids) AS (
  SELECT parent_id, id, ',' + cast(id as varchar(8000)) + ',' as ids
  FROM test_cte
  UNION ALL
  SELECT t.parent_id, r.id, ids + cast(id as varchar(8000)) + ','
  FROM test_cte t INNER JOIN 
       recursive_cte r
       ON r.root_id = t.id
  WHERE ',' + r.ids + ',' not like '%,' + cast(t.id as varchar(8000)) + ',%'
)
SELECT *
FROM recursive_cte
WHERE root_id = 0;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!