Delimiter //
/**
    In batchnum Int : num du lot, si 0 ou null traitement de l'ensembles des lignes
*/
Drop Procedure if exists LOADER_EDMINDEX_ATTACHED_DOCUMENTS_INSERT//
Create Procedure LOADER_EDMINDEX_ATTACHED_DOCUMENTS_INSERT (
    In batchnum int
    , In docsLastId Int
    , In attachedDocsLastId Int
)
Begin
	attachedDocInsert: Begin
		Insert Into ATTACHED_DOCUMENTS (
			ID_ATTACHED_DOCUMENTS, DOCUMENTS_ID_DOCUMENTS
			, ATTACHED_DOCUMENTS_DATE, ATTACHED_DOCUMENTS_TITLE
		)
		Select 
			src.ID_DOCUMENTS_NEW + attachedDocsLastId, src.ID_DOCUMENTS_NEW + docsLastId
			, Coalesce(src.DOCUMENTS_DATE, Curdate()), Coalesce(src.DOCUMENTS_TITLE, src.DOCUMENTS_NAME)
		From LOADER_EDMINDEX src  
			Inner Join LOADER_STATUS lst  
				On src.LOADER_STATUS_ID_LOADER_STATUS = lst.ID_LOADER_STATUS  
		Where lst.LOADER_STATUS_ERRCOUNT = 0  
            And lst.LOADER_STATUS_BATCH_NUM =  batchnum
            And Coalesce(src.ID_DOCUMENTS_NEW, 0) <> 0 
		;
	End;
	
End //

Delimiter ;


