Delimiter //
/**
    In batchnum Int : num du lot
*/

Drop Procedure if exists LOADER_REFDATA_REF_DATA_ACCOUNTS_REF_INSERT//

Create Procedure LOADER_REFDATA_REF_DATA_ACCOUNTS_REF_INSERT (
    In batchnum int
    , In lastid int
)
Begin

	insertNewsAccRef: Begin
        Insert Into ACC_REF_DATAS (ACCOUNTS_ID_ACCOUNTS, ENT_REF_DATAS_ID_ENT_REF_DATAS)
        Select LARD.ACCOUNTS_ID_ACCOUNTS, Coalesce(LARD.ID_ENTITIES_REF_DATAS, LARD.NEW_ID_ENTITIES_REF_DATAS + lastid)
        From LOADER_REFDATA LARD
            Inner Join LOADER_STATUS LST
                On LARD.LOADER_STATUS_ID_LOADER_STATUS = LST.ID_LOADER_STATUS
        Where 
            LST.LOADER_STATUS_ERRCOUNT = 0  
            And LST.LOADER_STATUS_BATCH_NUM = batchnum
			And LARD.LOADER_REFDATA_TYPE Like '%ACCOUNTS'
			And Coalesce(LARD.ID_ENTITIES_REF_DATAS, LARD.NEW_ID_ENTITIES_REF_DATAS) Is Not Null
        ;
    end ;

End //

Delimiter ;