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
lopezclopezc 

System.Exception: Too many SOQL queries: 21

Hi,

I am getting this error: caused by: System.Exception: Too many SOQL queries: 21  

and I know why, however I don't really know how to solve it, could you please help me with this?

Code:
trigger TaskAccountNumber on Task (before insert, before update) {

/***************************************************************************
* TaskBefore Trigger - TaskCoverage 29/9/08
*
* Description:
* Before a task is inserted/updated, look for a matching contact/lead and update
* Account_Number__c on the task.
*
* Notes:
* To avoid reaching Apex code built-in limits, the code is structured to keep
* the number of SOQL queries to an absolute minimum.
*
* Revision History
* none
****************************************************************************/

// List to hold the WhoId of all incoming task records
List<String> whoIdList = new String [] {};
for(Task loopTask : Trigger.New) {
whoIdList.add(loopTask.WhoId);
}
//issue one query to get all contacts for all incoming who ids (to avoid Apex restrictions)
List<Contact> matchingContacts = [SELECT Id, Account_Number__c from Contact where Id IN :whoIdList];
// issue one query to get all leadsfor all incoming who ids (to avoid Apex restrictions)
List<Lead> matchingLeads = [SELECT Id, Demo_Account__c from Lead where Id IN :whoIdList];

Map<String, Contact> foundContacts = new Map<String, Contact>();
for (Contact loopContact : matchingContacts) {
foundContacts.put(loopContact.Id, loopContact);
}

Map<String, Lead> foundLeads = new Map<String, Lead>();
for (Lead loopLead : matchingLeads) {
foundLeads.put(loopLead.Id, loopLead);
}
// loop through the incoming tasks again, for each, loop through the found contacts/leads to find matching record
// on Id
for(Task loopTask : Trigger.New) {
if (loopTask.WhoId != null) {
Contact foundContact = foundContacts.get(loopTask.WhoId);
if (foundContact != null) {
loopTask.Account_Number__c = foundContact.Account_Number__c;
}else{
Lead foundLead = foundLeads.get(loopTask.WhoId);
if(foundLead != null){
loopTask.Account_Number__c = foundLead.Demo_Account__c;
}
}
}
}
}

 Many Thanks!

dgindydgindy
Try putting a limit 100 at the end of it. 
SuperfellSuperfell
What other triggers on task do you have ?
lopezclopezc
just one.. if I put limit 100 it won't return all the records, so probably I won't be able to find the contact/lead even if it exist...