function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Krishna_225Krishna_225 

ContatctoAccount: System.LimitException: Apex CPU time limit exceeded

Hello Developers, 
I have a code which executes when a new contact is inserted or updated. But when i tried to insert bulk contacts through data loader, the system is throwing following error "ContatctoAccount: System.LimitException: Apex CPU time limit exceeded".
Below is my code
trigger ContatctoAccount on Contact (after insert, after update) {

    list<Contact> Cont = new list<Contact>();
  list<Account> Acc = [select id,Account_code__c from Account where Account_code__c != Null];
    for(Contact Cnt : trigger.new){        
        if(Acc.size()>0){
            for(Account a : Acc){
                for(Contact c: trigger.new){
                    if(c.Account_code__c == a.Account_code__c){
                     c.AccountID = a.id;
                        }
                    Cont.add(c);
                }
            }
        }
    }
}

Can anyone from here please help me solving this error.
Thank you in advance
Krish
SandhyaSandhya (Salesforce Developers) 
Hi,

Try below code
trigger ContatctoAccount on Contact (after insert, after update) {

    list<Contact> Cont = new list<Contact>();
    Map<String,Account> accountCode = new Map<String,Account>();
    for(Account acc: [select id,Account_code__c from Account where Account_code__c != Null]){
        if(acc.Account_code__c!= null){
            accountCode.put(acc.Account_code__c, acc);
        }
    }
    for(Contact C : trigger.new){
        if(accountCode.containsKey(c.Account_code__c)){
            c.AccountID = accountCode.get(c.Account_code__c).id;
            Cont.add(c);
        }
    }
}

Refer below article

https://help.salesforce.com/articleView?id=000232681&language=en_US&type=1
 
Please mark it as solved if my reply was helpful. It will make it available for other as the proper solution.
                                             
Best Regards
Sandhya