Delimiter $$
/**
 * compute BUSINESS_COMPUTE_ACCOUNTS_DATA_NB_LINKED_ACCOUNTS
 * calcul le nombre de compte rattaché
 * rempli la table ACCOUNTS_COMPUTED_DATA, champ ACCOUNTS_COMPUTED_DATA_INT, clé NB_ACC_LNK
 */ 
Drop Procedure if Exists BUSINESS_COMPUTE_ACCOUNTS_DATA_NB_LINKED_ACCOUNTS $$
Create Procedure BUSINESS_COMPUTE_ACCOUNTS_DATA_NB_LINKED_ACCOUNTS(In idaccounts Int unsigned, In identities Int unsigned)
Begin
    acc_computed_data_nb_acc_lnk: begin

        if idaccounts Is null Then
            Set @bcadnla_accMinVal = 0;
            Set @bcadnla_accMaxVal = 4e7;
        Else
            Set @bcadnla_accMinVal = idaccounts;
            Set @bcadnla_accMaxVal = idaccounts;
        End if;

        if identities Is null Then
            Set @bcadnla_enttMinVal = 0;
            Set @bcadnla_enttMaxVal = 100;
        Else
            Set @bcadnla_enttMinVal = identities;
            Set @bcadnla_enttMaxVal = identities;
        End if;


        -- purge des données
        Delete ACCOUNTS_COMPUTED_DATA 
        From ACCOUNTS_COMPUTED_DATA
            Inner join ACCOUNTS acc
                on ACCOUNTS_COMPUTED_DATA.ACCOUNTS_ID_ACCOUNTS = acc.ID_ACCOUNTS
        Where ACCOUNTS_COMPUTED_DATA_KEY = 'NB_ACC_LNK'
			And ACCOUNTS_ID_ACCOUNTS between @bcadnla_accMinVal And @bcadnla_accMaxVal
            And acc.ENTITIES_ID_ENTITIES between @bcadnla_enttMinVal And @bcadnla_enttMaxVal
		;

        -- mise à jour des données
        Insert Into ACCOUNTS_COMPUTED_DATA (
            ACCOUNTS_ID_ACCOUNTS, ACCOUNTS_COMPUTED_DATA_KEY, ACCOUNTS_COMPUTED_DATA_INT
        )
        Select
            ACC.ID_ACCOUNTS, 'NB_ACC_LNK'
			, Count(ACCHACC.ID_ACCOUNTS_has_ACCOUNTS)
        From 
            ACCOUNTS ACC
            LEFT JOIN ACCOUNTS_has_ACCOUNTS ACCHACC
				On ACC.ID_ACCOUNTS = ACCOUNTS_ID_ACCOUNTS
		Where 
			ACC.ID_ACCOUNTS between @bcadnla_accMinVal And @bcadnla_accMaxVal
			And ACC.ENTITIES_ID_ENTITIES between @bcadnla_enttMinVal And @bcadnla_enttMaxVal
        
        Group By ACC.ID_ACCOUNTS
        ;
    end;
    
end $$
Delimiter ;

