Delimiter //
/**
    In batchnum Int : num du lot, si 0 ou null traitement de l'ensembles des lignes
*/
Drop Procedure if exists LOADER_ENTRIES_INSERT//
Create Procedure LOADER_ENTRIES_INSERT (
    In batchnum int, 
    In lastId Int
)
Begin
        Set @lei_curdate = curdate();
        Insert Into ENTRIES (
            ID_ENTRIES,
            DF_MATCH_STAT_ID_DF_MATCH_STAT, DF_SAND_STATE_ID_DF_SAND_STATE, ID_DF_PAY_SCHED_STATUS,
            DF_CURRENCIES_ID_DF_CURRENCIES, DF_ENTR_TYPE_ID_DF_ENTR_TYPE, DF_PAY_TYPE_ID_DF_PAY_TYPE, 
            ENTRIES_ACCOUTING_ACCOUNTS, ENTRIES_DATE, ENTRIES_DUE_DATE, 
            ENTRIES_LABEL, ENTRIES_PURCHASE_ORDER, ENTRIES_REF , 
            ENTRIES_DEBIT, ENTRIES_CREDIT, ENTRIES_ADMIN_DEBIT, ENTRIES_ADMIN_CREDIT, ENTRIES_ENT_DEBIT, ENTRIES_ENT_CREDIT, 
            ENTRIES_ENT_BALANCE, DF_ENTR_STT_ID_DF_ENTR_STT, ENTRIES_PROMISE, ENTRIES_PROMISE_DATE,
            CONTACTS_ID_CONTACTS, ENTRIES_CREATION_DATE
        )
        Select
            src.ID_ENTRIES_NEW + lastId,
            src.DF_MATCH_STAT_ID_DF_MATCH_STAT, src.DF_SAND_STATE_ID_DF_SAND_STATE, src.DF_PAY_SCHED_STATUS_ID_DF_PAY_SCHED_STATUS,
            src.DF_CURRENCIES_ID_DF_CURRENCIES, src.DF_ENTR_TYPE_ID_DF_ENTR_TYPE, src.DF_PAY_TYPE_ID_DF_PAY_TYPE, 
            src.ENTRIES_ACCOUTING_ACCOUNTS, src.ENTRIES_DATE, src.ENTRIES_DUE_DATE,
            src.ENTRIES_LABEL, src.ENTRIES_PURCHASE_ORDER, src.ENTRIES_REF , 
            Coalesce(src.ENTRIES_DEBIT, 0), Coalesce(src.ENTRIES_CREDIT, 0), Coalesce(src.ENTRIES_ADMIN_DEBIT, 0), Coalesce(src.ENTRIES_ADMIN_CREDIT, 0), Coalesce(src.ENTRIES_ENT_DEBIT, 0), Coalesce(src.ENTRIES_ENT_CREDIT, 0), 
            src.ENTRIES_ENT_BALANCE, src.DF_ENTR_STT_ID_DF_ENTR_STT, Coalesce(ENTRIES_PROMISE, 0), ENTRIES_PROMISE_DATE,
            src.CONTACTS_ID_CONTACTS,  @lei_curdate
        From
                LOADER_ENTRIES src  

                Inner Join LOADER_STATUS lst  
                    On src.LOADER_STATUS_ID_LOADER_STATUS = lst.ID_LOADER_STATUS  
        Where 1 = 1  
            And lst.LOADER_STATUS_ERRCOUNT = 0  
            And lst.LOADER_STATUS_BATCH_NUM = batchnum
            And Coalesce(src.ID_ENTRIES_NEW, 0) <> 0 
        ;

End //

Delimiter ;


