Delimiter //
/**
    In batchnum Int : num du lot
*/
Drop Procedure if exists LOADER_RECLAIMS_SUMMARIES_INSERT//
Create Procedure LOADER_RECLAIMS_SUMMARIES_INSERT (
    In batchnum int
    , In lastId Int
)
Begin
		
        Insert Into SUMMARIES (
			ACCOUNTS_ID_ACCOUNTS, ENTRIES_ID_ENTRIES
			, DF_SUMMARIES_ID_DF_SUMMR, DF_PRIORITY_ID_DF_PRIORITY
			, SUMMARIES_DATE, SUMMARIES_MEMBER_AUTHOR, SUMMARIES_OUTSTANDING
			, RECLAIMS_ID_RECLAIMS
        )  
        Select 
			src.ACCOUNTS_ID_ACCOUNTS, src.ENTRIES_ID_ENTRIES
			, DFSM.ID_DF_SUMMARIES, DFSM.DF_PRIORITY_ID_DF_PRIORITY
			,  Coalesce(src.RECLAIMS_CREATED, curdate()), src.MEMBERS_ID_MEMBERS, src.RECLAIMS_ORIGINAL_AMOUNT
			, Coalesce(src.ID_RECLAIMS, src.NEW_ID_RECLAIMS + lastId)
        From  
            LOADER_RECLAIMS src  
            Inner Join LOADER_STATUS lst  
                On src.LOADER_STATUS_ID_LOADER_STATUS = lst.ID_LOADER_STATUS  
			Inner Join DF_SUMMARIES DFSM
				On src.SUMMARIES_ID_SUMMARIES = DFSM.ID_DF_SUMMARIES
        Where 
            lst.LOADER_STATUS_ERRCOUNT = 0  
            And lst.LOADER_STATUS_BATCH_NUM =  batchnum
        ;
End //

Delimiter ;
