Delimiter $$
/**
 * compute BUSINESS_FI_ANA_TMP_ENTRIES_LAST_MATCHING_CODES
 * optimisation pour le calcul fiana
 * création de la table temporaire tmp_ent_last_match
 * contient le dernier lettrage par mouvement
 */ 
Drop Procedure if Exists BUSINESS_FI_ANA_TMP_ENTRIES_LAST_MATCHING_CODES $$
Create Procedure BUSINESS_FI_ANA_TMP_ENTRIES_LAST_MATCHING_CODES(In refdate DateTime, In idaccounts Int unsigned, In identities Int unsigned)
Begin
    v_ent_last_match: begin
	
-- 		set @accFilter = ifnull(idaccounts, '%');
        if idaccounts Is null Then
            Set @bftelmc_accMinVal = 0;
            Set @bftelmc_accMaxVal = 4e7;
        Else
            Set @bftelmc_accMinVal = idaccounts;
            Set @bftelmc_accMaxVal = idaccounts;
        End if;

        if identities Is null Then
            Set @bftelmc_enttMinVal = 0;
            Set @bftelmc_enttMaxVal = 1000;
        Else
            Set @bftelmc_enttMinVal = identities;
            Set @bftelmc_enttMaxVal = identities;
        End if;

        call BUSINESS_COMPUTE_ENTRIES_DATA_MATCHINGCODES_LAST(refdate, idaccounts, identities);
        Drop Temporary Table If Exists tmp_ent_last_match;
--         Create Temporary Table tmp_ent_last_match AS
        Create Temporary Table tmp_ent_last_match (
                    ID_ENTRIES Int Unsigned Not Null
                    , MATCHINGCODES_DATE Date
                    , Index (ID_ENTRIES)
                    , Index (MATCHINGCODES_DATE)
                )
            ;
        Insert Into tmp_ent_last_match (
                ID_ENTRIES, MATCHINGCODES_DATE
            )
            Select
                ID_ENTRIES, MATCHINGCODES_DATE
            From
                V_ENTRIES_MATCHINGCODES_LAST
			Where V_ENTRIES_MATCHINGCODES_LAST.ID_ENTRIES In (
                        Select  EHA.ENTRIES_ID_ENTRIES
                        From ENTRIES_has_ACCOUNTS EHA
                             Inner Join ACCOUNTS acc
                                        On EHA.ACCOUNTS_ID_ACCOUNTS = acc.ID_ACCOUNTS
                        Where 
#                             EHA.ACCOUNTS_ID_ACCOUNTS Between @bftelmc_accMinVal And @bftelmc_accMaxVal
                            acc.ID_ACCOUNTS Between @bftelmc_accMinVal And @bftelmc_accMaxVal
                            And acc.ENTITIES_ID_ENTITIES Between @bftelmc_enttMinVal And @bftelmc_enttMaxVal
                            And V_ENTRIES_MATCHINGCODES_LAST.ID_ENTRIES = EHA.ENTRIES_ID_ENTRIES
                    )
        ;
--         Create Index ix_tmp_ent_last_match_0 On tmp_ent_last_match(ID_ENTRIES);
--         Create Index ix_tmp_ent_last_match_1 On tmp_ent_last_match(MATCHINGCODES_DATE);

    end;
end $$
Delimiter ;