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

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

        Update
            LOADER_STATUS S
            Inner Join
                LOADER_ATTACHEDMEMBERS ATTMBR
                On ATTMBR.LOADER_STATUS_ID_LOADER_STATUS = S.ID_LOADER_STATUS
            Inner Join ACCOUNTS A
                On A.ACCOUNTS_REF = ATTMBR.ACCOUNTS_REF
                And A.ENTITIES_ID_ENTITIES = @idEntities
        Set
            ATTMBR.ACCOUNTS_ID_ACCOUNTS = A.ID_ACCOUNTS
        Where
            S.LOADER_STATUS_BATCH_NUM = batchnum
            And Coalesce(ATTMBR.ACCOUNTS_REF, '') != ''
        ;

        -- maj des erreur

        Update
            LOADER_STATUS S
            Inner Join
                LOADER_ATTACHEDMEMBERS ATTMBR
                On ATTMBR.LOADER_STATUS_ID_LOADER_STATUS = S.ID_LOADER_STATUS
        Set
            S.LOADER_STATUS_ERRCOUNT = Coalesce(S.LOADER_STATUS_ERRCOUNT, 0) + 1
            , S.LOADER_STATUS_ERRMSGS = LOADER_CONCAT_ERR(S.LOADER_STATUS_ERRMSGS, Concat('Référence de compte inexistante :', ATTMBR.ACCOUNTS_REF ) )
        Where 
            S.LOADER_STATUS_BATCH_NUM = batchnum
            And Coalesce(ATTMBR.ACCOUNTS_REF, '') != ''
            And ATTMBR.ACCOUNTS_ID_ACCOUNTS Is Null
        ;

    End ;
End//
Delimiter ;