I hava data in an Oracle table that is organized as a graph that can contain cycles (see example).
CREATE TABLE T (parent INTEGER, child INTEGER)
This might help until visited exceeds 4000 bytes. Cycles should not be possible but the line is there just as an example.
WITH descendants(node, lvl, pth, visited) AS
(
SELECT child node, 1, cast(child as varchar2(4000)), '/'||listagg(child,'/') within group (order by child) over()||'/'
FROM t
where parent = 2
UNION ALL
SELECT child, lvl+1, pth||'/'||child, D.visited||listagg(child,'/') within group (order by child) over()||'/'
FROM T
INNER JOIN descendants D
ON T.parent = D.node
WHERE D.visited not like '%/'||child||'/%'
)
cycle node set cyc to '1' default '0'
SELECT distinct node
FROM descendants
order by node
;