+ Start a Discussion
Todd B.Todd B. 

Too many SOQL queries

I wrote the following Class to update a field based on a value in the User table
public with sharing class SDMR_Enrollment_Cycles_Trigger_Handler {

    Public SDMR_Enrollment_Cycles_Trigger_Handler(){
        }
    Public void OnBeforeUpdate(SD_Mbr_Enroll_Cycles__c[] newCycles){    
        For (SD_Mbr_Enroll_Cycles__c c : newcycles){

            // Look up the User Id for the Unassigned user record, to be used when the Enrollment Credit Agent 
            // field is null 
            List<User> users = [Select id, LastName from User Where LastName='Unassigned' and isActive=True
                             Limit 1];
            Map<string, string> uservalues = new Map<string, string>{};
            For(User u2: users)
                uservalues.put(u2.LastName,u2.id);
            
// Populates the Enrollment Credit Agent L/U if the Enrollment Status field = "Enrolled" and the Use Me field = True
            If(c.Enrollment_Status__c == 'Enrolled' && c.Use_Me__c == True){
                    if(c.Enrollment_Credit_Agent__c!=null){       
                        c.Enrollment_Credit_Agent_L_U__c = c.Enrollment_Credit_Agent__c;}
// If the Enrollment Credit Agent L/U is null and the Enrollment Status field = "Enrolled" and the Use Me field = True
// then look up the User Id for the Unassigned user record.
                Else {c.Enrollment_Credit_Agent_L_U__c = uservalues.get('Unassigned') ;}
                       
        }   
        }
    }    
}
But I keep getting an error when I try and validate it in prodcution.  This is the line being flagged:  
List<User> users = [Select id, LastName from User Where LastName='Unassigned' and isActive=True Limit 1];

Component Errors
Error Message
0 0 SCEBSDMEC_TEST.EnrollmentBase_Enrolled_Batchable(), Details: System.LimitException: Too many SOQL queries: 101 Class.SDMR_Enrollment_Cycles_Trigger_Handler.OnBeforeUpdate: line 10, column 1 Trigger.SDMR_Enrollment_Cycles: line 6, column 1

Apex Test Failures
Error Message
SCEBSDMEC_TEST EnrollmentBase_Enrolled_Batchable System.LimitException: Too many SOQL queries: 101 
Stack Trace: Class.SDMR_Enrollment_Cycles_Trigger_Handler.OnBeforeUpdate: line 10, column 1 Trigger.SDMR_Enrollment_Cycles: line 6, column 1
BalajiRanganathanBalajiRanganathan
you should not use SOQL with in a for loop. try to move the SOQL outside of For Loop. Verify your SOQL and revist your logic.
Cloud_forceCloud_force
keeping select query within for loop is hitting the governers limit of 100 Queries per transaction. Place that query before for loop.

Thanks,
http://www.forcexplore.com/2014/08/visualforce-and-apex-tutorial-for-beginners.html