+ Start a Discussion
SalesforceCrm AccountCRMSalesforceCrm AccountCRM 

System.LimitException: Too many SOQL queries: 101 for trigger

Can any one help me out with this error:
System.LimitException: Too many SOQL queries: 101
I'm running a test class for a trigger  and the test class methods gets failed and the system throws an error for the other triggers 
System.LimitException: Too many SOQL queries: 101
Trigger.MergeLeadTrigger: line 276, column 1

The error line is :
conrecords=[select id , Rep_Managing_Partner_del__c from Contact where id in: getconid1 and Rep_Managing_Partner_del__c !=null];
        

System.LimitException: Too many SOQL queries: 101
Trigger.Accountduplicate: line 6, column 1
The error line is :
  lstusr  =[SELECT Id,Name,Profile.Name FROM User WHERE Id=:UserInfo.getuserId()];
Trigger which i run :
trigger CampaignMemberSyncStatus on CampaignMember (after update) {
    // Sync response status on Campaign Member to lead or contact

    // Look for status changes
    List<Id> relatedIDs = new List<ID>();
    List<Id> modifiedIDs = new List<ID>();
 
    // Get the list of IDs for campaignmembers whose status changed
    for(CampaignMember cm : Trigger.new) {
        if(cm.Response_Status__c != trigger.oldMap.get(cm.Id).Response_Status__c)
        {
            modifiedIDs.add(cm.Id);
            if(cm.ContactId != null) {
                relatedIDs.add(cm.ContactId);
            } else {
                relatedIDs.add(cm.LeadId);
            }
        }
    }
    if(modifiedIds.size() == 0) return;     /// No modified responses
    
    // Now pull the list of related leads and contacts
    Map<id,Lead> RelatedLeads;
    Map<id,Contact> RelatedContacts;
    RelatedLeads = new Map<ID,Lead>([Select id, Disqaulified_Reason__c, Status from Lead where Id in :relatedIDs]);
    RelatedContacts = new Map<ID,Contact>(
        [Select id, Status__c, Lead_Score__c, Campaign_Score__c, Account.Customer_Status__c, Admin_Nurture_Timeout__c from Contact where Id in :relatedIDs]);
    
    // Build lists of leads or contacts to update
    Map<ID,Lead> ModifiedLeads = new Map<ID,Lead>();
    Map<ID,Contact> ModifiedContacts = new Map<ID,Contact>();
    
    Map<String, CMStatusSettings__c> statusmapping = CMStatusSettings__c.getall();
    
    // Now update the stautus
    for(id cmid : modifiedIDs) {
        CampaignMember cm = trigger.newMap.get(cmid);
        Boolean wasupdated;
        if(cm.ContactId != null) {
            wasupdated = CampaignMemberFunctions.SyncStatus(cm, null, RelatedContacts.get(cm.ContactId), statusmapping);
            if(wasupdated) ModifiedContacts.put(cm.ContactID,RelatedContacts.get(cm.ContactId));
        } else {
            wasupdated = CampaignMemberFunctions.SyncStatus(cm, RelatedLeads.get(cm.LeadId), null, statusmapping);
            if(wasupdated) ModifiedLeads.put(cm.LeadId,RelatedLeads.get(cm.LeadId));
        }
    }
    if(ModifiedLeads.size()>0) update ModifiedLeads.values();
    if(ModifiedContacts.size()>0) update ModifiedContacts.values();
    }
Test Class :
@isTest
public class TestCampaignMemberSync 
{

    static testMethod void TestStatusUpdates() 
    {
    Account genericaccount = new Account(Name = 'someaccount');
    insert genericaccount;

        Lead ld1 = new Lead(Company='colead1',LastName='colead1');
        Lead ld2 = new Lead(Company='colead2',LastName='colead2');
        Contact ct1 = new Contact(LastName='cocontact1', AccountID = genericaccount.Id);
        Contact ct2 = new Contact(LastName='cocontact2', AccountID = genericaccount.Id);
        Campaign cam = new Campaign(Name='campname');
        insert cam;
    insert ld1;
    insert ld2;
    insert ct1;
    insert ct2;
        CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id, LeadId=ld1.Id, Buyer__c='a', user__c='b');
        CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id, Buyer__c='a', user__c='b');
        CampaignMember mc3 = new CampaignMember(CampaignId = cam.Id, ContactId=ct1.Id, Buyer__c='a', user__c='b');
        CampaignMember mc4 = new CampaignMember(CampaignId = cam.Id, ContactId=ct2.Id, Buyer__c='a', user__c='b');
    List<CampaignMember> cms = new List<CampaignMember>();
    cms.add(mc1);cms.add(mc2);cms.add(mc3);cms.add(mc4);
    
    
        insert cms;
        List<Id> cmids = new List<id>();
    for(CampaignMember thiscm: cms)
    {
      cmids.add(thiscm.id);
    }
    
    ld1.admin_CMSourceId__c = mc1.id;
    update ld1;  // Needed later to simulate the button click on conversion
    ld2.admin_CMSourceId__c = mc2.id;
    update ld2; // Needed later to simulate the button click on conversion
    
    // Initialize the opp for later creation from CampaignMember
    Opportunity Opp = new Opportunity(CloseDate = Date.Today().addDays(30), AccountId = genericaccount.Id,
        Name='someopp', StageName='Selected' );
        
        Test.StartTest();
        mc1.Response_Status__c = 'Working';
        mc2.Response_Status__c = 'Disqualified';
        mc2.Disqualified_Reason__c = 'no budget';
        mc3.Response_Status__c = 'Working';
        mc4.Response_Status__c = 'Disqualified';
        mc4.Disqualified_Reason__c = 'no budget';
        mc4.Do_not_reassign_to_Landings__c = true;
        
        update cms;
       Test.StopTest();    
        
        List<CampaignMember> mcres = [Select Id, Response_Status__c, Contact.Admin_Nurture_Timeout__c , Contact.Status__c, Lead.Status, Do_not_reassign_to_Landings__c 
          from CampaignMember where Id = :cmids ];
        for(CampaignMember cm: mcres) {
          System.debug('Response ' + cm.Response_Status__c + ' lead status:' + cm.Lead.Status + ' contact status:' + cm.Contact.Status__c );
          System.debug('Nurture date:' + mcres[3].Contact.Admin_Nurture_Timeout__c);
        }
    //System.assertEquals(mcres[3].Do_not_reassign_to_Landings__c, mcres[3].Contact.Do_not_reassign_to_Landings__c);
 
     }
   static testMethod void TestConversionsNoOpp() 
    {
        Account genericaccount = new Account(Name = 'someaccount');
        insert genericaccount;

            Lead ld1 = new Lead(Company='colead1',LastName='colead1');
            Lead ld2 = new Lead(Company='colead2',LastName='colead2');
            ld2.OwnerId = UserInfo.getUserId();
            Campaign cam = new Campaign(Name='campname');
            insert cam;
            insert ld1;
            insert ld2;
            CampaignMember mc1 = new CampaignMember(CampaignId = cam.Id, LeadId=ld1.Id, Buyer__c='a', user__c='b');
            CampaignMember mc2 = new CampaignMember(CampaignId = cam.Id, LeadId=ld2.Id, Buyer__c='a', user__c='b');
            List<CampaignMember> cms = new List<CampaignMember>();
            cms.add(mc1);
            cms.add(mc2);
        
            insert cms;
            List<Id> cmids = new List<id>();
            /*for(CampaignMember thiscm: cms)
            {
              cmids.add(thiscm.id);
            }*/
        
        ld1.admin_CMSourceId__c = mc1.id;
        update ld1;  // Needed later to simulate the button click on conversion
        ld2.admin_CMSourceId__c = mc2.id;
        update ld2; // Needed later to simulate the button click on conversion
        
        // Initialize the opp for later creation from CampaignMember
        Opportunity Opp = new Opportunity(CloseDate = Date.Today().addDays(30), AccountId = genericaccount.Id,
            Name='someopp', StageName='Selected' );
            
            mc1.Response_Status__c = 'Working';
            mc2.Response_Status__c = 'Disqualified';
            mc2.Disqualified_Reason__c = 'no budget';
             
            
            update cms;
            
            // We're checking CampaignMemberOpportunityInsertTrigger here
            Opp.admin_CMSourceId__c = mc2.Id;  // Set the source ID
            insert Opp;

            Test.StartTest();

            
            // Now let's do a lead convert
         Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(ld2.Id);
        lc.setConvertedStatus('Converted - Existing Opportunity');
        lc.setDoNotCreateOpportunity(true);
        lc.setOwnerId(UserInfo.getUserId());
        Database.LeadConvertResult lcr2 = Database.convertLead(lc);
            
              Test.StopTest();    
            try
            {
             }
            catch(Exception ex)
            {
              System.Debug('Exception during TestConversionsNoOpp StopTest (async error)' + ex.getMessage());
            }
     
         System.assert(lcr2.isSuccess());
            CampaignMember mc2b = [Select Id,Response_Status__c, Opportunity_Create_Date__c, Opportunity_Name__c, Buyer__c, User__c from CampaignMember where Id = :mc2.id];
        Lead convertedleadinfo = [Select Id, isConverted, Status from Lead where id = :ld2.Id];
        System.Debug('original leadid:' + ld2.Id + ' leadid result id:' + lcr2.getLeadId());
        System.Debug('Converted lead isconverted:' + convertedleadinfo.IsConverted + ' status:' + convertedleadinfo.Status);
           system.assertEquals('Converted - Existing Opportunity', mc2b.Response_Status__c);
     }
 }
Any help very much appreciated.



 
pconpcon
This is likely not because of that query in specific, but it is likely because that is the last query that happens to hit the limit. You can reduce the number of queries you are hitting by inserting your setup objects (such as Leads and Contacts) in a single insert instead of multiple.  Also, you should wrap your insertion of CampaignMember in a Test.startTest() and Test.stopTest().  This will reset the DML / SOQL limits for your test.
SaurabhGupta_SaurabhGupta_
Put all your SOQL and dml operations out of loop. This will resolve your issue.