Delimiter //
Drop Procedure If Exists LOADER_EDMINDEX_NORMALIZE_MAP_ENTRIES_ACC_EXT_REF_PROVIDED//
Create Procedure LOADER_EDMINDEX_NORMALIZE_MAP_ENTRIES_ACC_EXT_REF_PROVIDED(
    In batchnum Int
)
Begin
    
        -- identification de l'écriture par la référence "externe" de l'ecriture
		-- => on insert les ligne correspondants aux ecritures 
		-- dans la table LOADER_CREATE_TABLE_EDMINDEX_ENTRIES_HAS_DOCUMENTS
		Insert Into LOADER_EDMINDEX_ENTRIES_HAS_DOCUMENTS (
			LOADER_STATUS_ID_LOADER_STATUS
            , LOADER_EDMINDEX_ID_LOADER_EDMINDEX
            , ENTRIES_ID_ENTRIES
		)
		Select
			LST.ID_LOADER_STATUS
            , LEDM.ID_LOADER_EDMINDEX
            , EHA.ENTRIES_ID_ENTRIES
		From
			LOADER_EDMINDEX LEDM
            Inner Join LOADER_STATUS LST
                On LST.ID_LOADER_STATUS = LEDM.LOADER_STATUS_ID_LOADER_STATUS
            Inner Join ENTRIES_has_ACCOUNTS EHA
                On LEDM.ACCOUNTS_ID_ACCOUNTS = EHA.ACCOUNTS_ID_ACCOUNTS
                And LEDM.ENTRIES_ACC_EXT_REF = EHA.ENTRIES_ACC_EXT_REF
		Where
            LST.LOADER_STATUS_BATCH_NUM = batchnum
            And LEDM.LOADER_EDMINDEX_TYPE  = 'ENTRIES'
            And Coalesce(LEDM.ENTRIES_ACC_EXT_REF, '') != ''
            And EHA.ENTRIES_PERMANENT_ATTACHEMENT = 1
		;

End//
Delimiter ;