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
Kon DeleKon Dele 

Too many SOQL Queries 101

Hey Yall,
How could I adjust the trigger code below and move the SOQL Query from inside the FOR loop?
trigger OLISyncQLIFields on OpportunityLineItem (before insert,before update) {

    date vServiceEnd;
    date vServiceStart;
    string vQuoteId;
    string vPricebookEntryId;
    string vOpportunity;
 
    for(OpportunityLineItem oppLine : Trigger.new){
           
        vQuoteId = oppLine.QuoteId__c;
        vPricebookEntryId = oppLine.PricebookEntryId;
        
        for(QuoteLineItem quoteLine : [select Id, Service_Start__c, Service_End__c from QuoteLineItem where (QuoteId = :vQuoteId and PricebookEntryId = :vPricebookEntryId)]){
            
            vServiceEnd = quoteline.Service_End__c;
            VServiceStart = quoteline.Service_Start__c;
         
        }
        
        oppLine.ServiceEndDate__c = vServiceEnd;
        oppLine.ServiceStartDate__c = vServiceStart;
        
    }
}

 
KaranrajKaranraj
Try the below code 
trigger OLISyncQLIFields on OpportunityLineItem (before insert,before update) {

date vServiceEnd;
date vServiceStart;
string vQuoteId;
string vPricebookEntryId;
string vOpportunity;
List<Id> listQuoteIds = new List<Id>();
List<id> listProcebookId = new List<Id>();

for(OpportunityLineItem oppLine : Trigger.new){
listQuoteIds = oppLine.QuoteId__c;
listProcebookId = oppLine.PricebookEntryId;
}
List<QuoteLineItem> qlt = [select Id, Service_Start__c, Service_End__c from QuoteLineItem where (QuoteId = :listQuoteIds and PricebookEntryId = :listProcebookId)];

for(OpportunityLineItem oppLine : Trigger.new){
for(QuoteLineItem ql : qlt){
if(ql.QuoteId == oppLine.QuoteId__c && ql.PricebookEntryId == oppLine.PricebookEntryId){
oppLine.ServiceEndDate__c = al.Service_End__c;;
oppLine.ServiceStartDate__c = quoteline.Service_Start__c;
}
}
}
}

Check the apex best practice documention here https://developer.salesforce.com/page/Apex_Code_Best_Practices