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

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

    Update
        LOADER_STATUS S
        Inner Join
            LOADER_SUMMARIES 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
    ;

    -- maj des erreur

    Update
        LOADER_STATUS S
        Inner Join
            LOADER_SUMMARIES 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
    ;

#     Update
#         LOADER_STATUS ldts
#         Inner Join
#             LOADER_SUMMARIES ldsmr
#             On ldsmr.LOADER_STATUS_ID_LOADER_STATUS = ldts.ID_LOADER_STATUS
#         Left Join ACCOUNTS acc
#             On acc.ACCOUNTS_REF = ldsmr.ACCOUNTS_REF
#             And acc.ENTITIES_ID_ENTITIES = @idEntities
#     Set
#         ldsmr.ACCOUNTS_ID_ACCOUNTS = acc.ID_ACCOUNTS
#         , ldts.LOADER_STATUS_ERRCOUNT = S.LOADER_STATUS_ERRCOUNT + (
#                     Case When acc.ID_ACCOUNTS Is Null Then 1 Else 0 End
#                 )
#         , ldts.LOADER_STATUS_ERRMSGS = LOADER_CONCAT_ERR(S.LOADER_STATUS_ERRMSGS
#                                             , Case When acc.ID_ACCOUNTS Is Null
#                                                     Then
#                                                         Concat('Référence de compte inexistante :', ldsmr.ACCOUNTS_REF )
#                                                     Else
#                                                         ''
#                                                     End
#                                         )
#     Where
#         ldts.LOADER_STATUS_BATCH_NUM = batchnum
#         And Coalesce(ldsmr.ACCOUNTS_REF, '') != ''
#     ;

End//
Delimiter ;