I have 2 tables:
PLAN_Type_FIRST_ETAP_Type:
PLAN_Type_Id | ETAP_TypeFirst_Id
----------------+---------------------
1 | 5
2 | 9
3 | 8
ETAP_TypeTransition:
PLAN_Type_Id | ETAP_Type_Id | ETAP_TypeNext_Id
----------------+-------------------+----------------------
2 | 6 | 7
3 | 8 | 9
2 | 7 | 10
2 | 11 | NULL
3 | 9 | 8
2 | 10 | 11
For a PLAN_Type_Id there's a ETAP_TypeFirst_Id, then we find it in the other table, then we take the ETAP_TypeNext_Id then we take the ETAP_Type_Id that is the same of the ETAP_Type_Id.
So we have etapes that are following each other for a plan.
So to order this i have made that :
WITH CTEA (id_plan, id_firstetp)
AS
(
SELECT distinct p.PLAN_Type_Id as id_plan, p.ETAP_TypeFirst_Id as id_firstetp
from PLAN_Type_FIRST_ETAP_Type p
where p.ETAP_TypeFirst_Id is not null
),
cte (id_plan,id_firstetp, etp_next)
AS (SELECT c.id_plan, et.ETAP_Type_Id, et.ETAP_TypeNext_Id as etp_next
from ETAP_TypeTransition as et inner join CTEA as c
on c.id_plan=et.PLAN_Type_Id and c.id_firstetp=et.ETAP_Type_Id
UNION ALL
SELECT et.PLAN_Type_Id, et.ETAP_Type_Id, et.ETAP_TypeNext_Id
FROM cte inner join ETAP_TypeTransition et
on etp_next=et.ETAP_Type_Id and et.PLAN_Type_Id=id_plan
)
select * from cte order by id_plan
The problem is because of the rows
PLAN_Type_Id | ETAP_Type_Id | ETAP_TypeNext_Id
----------------+-------------------+----------------------
3 | 8 | 9
3 | 9 | 8
I have the message:
L'instruction a été terminée. La récursivité maximale 100 a été épuisée avant la fin de l'instruction.
I have made that because my goal is to select in this example values : 3 ---- 8 ---- 9, which produce a loop. There can be several loops (but just one by plan).
Expected output
3 ---- 8 ---- 9
How can i achieve that ?