
Delimiter //
Drop Procedure If Exists LOADER_EDMINDEX_NORMALIZE_MAP_ENTRIES_REF_PROVIDED//
Create Procedure LOADER_EDMINDEX_NORMALIZE_MAP_ENTRIES_REF_PROVIDED(
    In batchnum Int
)
Begin
		Set @ld_edm_ix_ent_identity = GET_LOADER_INFO('ID_ENTITIES', batchnum);
		-- identification de l'écriture par la référence de l'ecriture
		-- => plusieur ecritures peuvent avoir la même référence
		-- => 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
		)
        -- explain
		Select
			LST.ID_LOADER_STATUS
            , LEDM.ID_LOADER_EDMINDEX
            , ENT.ID_ENTRIES
            
		From
			LOADER_EDMINDEX LEDM
            Inner Join LOADER_STATUS LST
                On LST.ID_LOADER_STATUS = LEDM.LOADER_STATUS_ID_LOADER_STATUS
            
			Inner Join (
                ACCOUNTS ACC
                Inner Join ENTRIES_has_ACCOUNTS EHA
                    On EHA.ACCOUNTS_ID_ACCOUNTS = ACC.ID_ACCOUNTS
                        And EHA.ENTRIES_PERMANENT_ATTACHEMENT = 1
                Inner Join ENTRIES ENT
                    On ENT.ID_ENTRIES = EHA.ENTRIES_ID_ENTRIES
            ) On LEDM.ACCOUNTS_ID_ACCOUNTS = ACC.ID_ACCOUNTS
                And LEDM.ENTRIES_REF = ENT.ENTRIES_REF
		Where 
            LST.LOADER_STATUS_BATCH_NUM = @batchnum
            And LEDM.LOADER_EDMINDEX_TYPE  = 'ENTRIES'
            And Coalesce(LEDM.ENTRIES_REF, '') != ''
            And ACC.ENTITIES_ID_ENTITIES = @ld_edm_ix_ent_identity
			
-- 		Select
-- 			LST.ID_LOADER_STATUS, ENT.ID_ENTRIES
-- 		From
-- 			LOADER_EDMINDEX LEDM
--             Inner Join LOADER_STATUS LST
--                 On LST.ID_LOADER_STATUS = LEDM.LOADER_STATUS_ID_LOADER_STATUS
-- --             Inner Join 
-- --                 On 
-- 			Inner Join ENTRIES ENT
-- 				On LEDM.ENTRIES_REF = ENT.ENTRIES_REF
-- 		Where 
--             LST.LOADER_STATUS_BATCH_NUM = batchnum
--             And LEDM.LOADER_EDMINDEX_TYPE  = 'ENTRIES'
--             And Coalesce(LEDM.ENTRIES_REF, '') != ''
-- 			-- contrainte lié à l'entité
-- -- 			And ENT.ID_ENTRIES in (
-- 			And Exists (
-- 				Select 
-- 					EHA.ENTRIES_ID_ENTRIES
-- 				From ENTRIES_has_ACCOUNTS EHA
-- 					Inner Join ACCOUNTS ACC
-- 						On EHA.ACCOUNTS_ID_ACCOUNTS = ACC.ID_ACCOUNTS
--                         And EHA.ENTRIES_PERMANENT_ATTACHEMENT = 1;
-- -- 				Where LEDM.ACCOUNTS_ID_ACCOUNTS = EHA.ACCOUNTS_ID_ACCOUNTS
-- 				Where LEDM.ACCOUNTS_ID_ACCOUNTS = ACC.ID_ACCOUNTS
-- 					And ACC.ENTITIES_ID_ENTITIES = @ld_edm_ix_ent_identity
--                     And ENT.ID_ENTRIES = EHA.ENTRIES_ID_ENTRIES
--                 Limit 1
-- 			)
		;


End//
Delimiter ;