Delimiter //
/**
 * Map the given Account Ref to Account Id
 * @param int batchnum
 * @author Ben
 */
Drop Procedure If Exists LOADER_GUARANTEED_NORMALIZE_MAP_ACCOUNTS//
Create Procedure LOADER_GUARANTEED_NORMALIZE_MAP_ACCOUNTS(
    In batchnum Int
)
Begin
    
    Set @idEntities = GET_LOADER_INFO('ID_ENTITIES', batchnum);

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

    -- Maj des erreurs
    Update
        LOADER_STATUS S
        Inner Join
            LOADER_GUARANTEED LDR
            On LDR.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 :', LDR.ACCOUNTS_REF ) )
    Where 
        S.LOADER_STATUS_BATCH_NUM = batchnum
        And Coalesce(LDR.ACCOUNTS_REF, '') != ''
        And LDR.ACCOUNTS_ID_ACCOUNTS Is Null
    ;

End//
Delimiter ;