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

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

    Update
        LOADER_STATUS S
        Inner Join
            LOADER_RECLAIMS ARD
            On ARD.LOADER_STATUS_ID_LOADER_STATUS = S.ID_LOADER_STATUS
        Inner Join ACCOUNTS A
            On A.ACCOUNTS_REF = ARD.ACCOUNTS_REF
            And A.ENTITIES_ID_ENTITIES = @idEntities
    Set
        ARD.ACCOUNTS_ID_ACCOUNTS = A.ID_ACCOUNTS
    Where
        S.LOADER_STATUS_BATCH_NUM = batchnum
		And S.LOADER_STATUS_ERRCOUNT = 0
    ;

    -- maj des erreur

    Update
        LOADER_STATUS S
        Inner Join
            LOADER_RECLAIMS ARD
            On ARD.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('Référence de compte inexistante :', ARD.ACCOUNTS_REF ) )
    Where 
        S.LOADER_STATUS_BATCH_NUM = batchnum
        And Coalesce(ARD.ACCOUNTS_REF, '') != ''
        And ARD.ACCOUNTS_ID_ACCOUNTS Is Null
    ;

End//
Delimiter ;