I am getting error as \"ORA-32044: cycle detected while executing recursive WITH query\" while executing the following query in Oracle.
WITH EmpsCTE (affiliation
Your code will working fine except only for one data condition that is when your to_customer (1000022560394) himself have started the transaction in the first place and after some level of transaction its being returned to him only.
Eg- Sample Data Set
For this case, your Recursive part of query will find all its conditions true even at the end of the transaction, for the data will be there both in your normal table and incremental dataset.
One solution is to create a match-flag to determine its number of encounter and avoid infinite loop:
WITH EmpsCTE (affiliation_id, from_customer_id,to_customer_id, to_name,level1,match_count)
AS
(
SELECT affiliation_id, from_customer_id,to_customer_id, to_name, 0, 0 match_count
FROM affiliation aff
WHERE to_customer_id != from_customer_id
and to_customer_id = 1000022560394
UNION ALL
SELECT aff.affiliation_id, aff.from_customer_id,aff.to_customer_id, aff.to_name, m.level1 + 1,1 match_count
FROM affiliation aff
INNER JOIN EmpsCTE m
ON aff.to_customer_id = m.from_customer_id
where m.match_count=0
)
SELECT * FROM EmpsCTE;