Azure Synapse SQL - alternative for recursive CTE

Viewed 68

I am making my first steps in Synapse. I just learned that recursive CTEs cannot be executed, so I am looking for an alternative for this code:

with newFaktTableAllBoxesLabeled as (
    SELECT 
       m.[READ_TIME]
      ,m.[KYOTEN_CODE]
      ,m.[KOUTEI_CODE]
      ,m.[MAIN_EPC_DATA]
      ,m.[MAIN_HINSYU]
      ,m.[UNIT_EPC_DATA]
      ,m.[UNIT_HINSYU]
      ,m.[DENPYO_NO]
      ,m.[HIMO_FLG]
      ,m.[BOXID]
    FROM newFaktTableWithFirstBoxID m
    WHERE m.[UNIT_EPC_DATA] IS NOT NULL

    UNION ALL 

    SELECT 
         b.[READ_TIME]
        ,b.[KYOTEN_CODE]
        ,b.[KOUTEI_CODE]
        ,b.[MAIN_EPC_DATA]
        ,b.[MAIN_HINSYU]
        ,b.[UNIT_EPC_DATA]
        ,b.[UNIT_HINSYU]
        ,b.[DENPYO_NO]
        ,b.[HIMO_FLG]
        
        ,COALESCE(b.[BOXID], t.BOXID) as BOXID
    FROM newFaktTableAllBoxesLabeled t
    JOIN newFaktTableWithFirstBoxID b ON b.[UNIT_EPC_DATA] = t.[MAIN_EPC_DATA]
)
SELECT  * FROM newFaktTableAllBoxesLabeled

Background Info Its a list with many boxes which get a new ID every time they are relabled. I already identified the first occurence of a box and gave it an ID (BOXID). Now I would like to allocate this ID also to the same box after it had been relabled. I always know a box identifier ([MAIN_EPC_DATA]) and its future identifier ([UNIT_EPC_DATA]) in one row. So my goal is to reference the current ID to the former ID ([MAIN_EPC_DATA] to [UNIT_EPC_DATA]) and get the ID which I created already (BOXID) and which currently is only available for the first occurence of a box (so withouth a parent).

Thats what the data looks like in a simplyfied way
what the data looks like now and what I want to achieve

I heard there is an option with a while loop, but I am not experienced enough to do that. I would be very happy for your help! Thank you!

0 Answers
Related