Delimiter //
/**
 * Find the id of the given account
 * 
 */
Drop Procedure If Exists LOADER_LINKEDACCOUNTS_NORMALIZE_MAP_ACCOUNTS_LINK//
Create Procedure LOADER_LINKEDACCOUNTS_NORMALIZE_MAP_ACCOUNTS_LINK(
    In batchnum Int
)
Begin
    

    Set @idEntities = GET_LOADER_INFO('ID_ENTITIES', batchnum);

    Update
        LOADER_STATUS S
        Inner Join
            LOADER_LINKEDACCOUNTS LNKAC
            On LNKAC.LOADER_STATUS_ID_LOADER_STATUS = S.ID_LOADER_STATUS
        Inner Join ACCOUNTS A
            On A.ACCOUNTS_REF = LNKAC.ACCOUNTS_REF_LINKED
            And A.ENTITIES_ID_ENTITIES = @idEntities
    Set
        LNKAC.ACCOUNTS_ID_ACCOUNTS_LINKED = A.ID_ACCOUNTS
    Where
        S.LOADER_STATUS_BATCH_NUM = batchnum
    ;

    -- maj des erreur

    Update
        LOADER_STATUS S
        Inner Join
            LOADER_LINKEDACCOUNTS LNKAC
            On LNKAC.LOADER_STATUS_ID_LOADER_STATUS = S.ID_LOADER_STATUS
    Set
        S.LOADER_STATUS_ERRCOUNT = S.LOADER_STATUS_ERRCOUNT + 1
        , S.LOADER_STATUS_ERRMSGS = LOADER_CONCAT_ERR(S.LOADER_STATUS_ERRMSGS, Concat('Compte rattaché inexistant :', LNKAC.ACCOUNTS_REF_LINKED ) )
    Where 
        S.LOADER_STATUS_BATCH_NUM = batchnum
        And Coalesce(LNKAC.ACCOUNTS_REF_LINKED, '') <> ''
        And LNKAC.ACCOUNTS_ID_ACCOUNTS_LINKED Is Null
    ;

End//
Delimiter ;