+ Start a Discussion

minimize the no of script statements

hey all,


Here's a simple trigger.


There are 2 for loops and a soql query to loop through.


comparing the WBS2 values, I update the WBS2 order from WBS_2_Order__c object to SPM object.


how can I refine it to reduce the no of script statements/no of soql queries? Using maps? (any samples)


trigger SPMUpdateWBS2Order on Site_Progress_Monitoring__c (before insert,before update) {

    List<WBS_2_Order__c> wbs2OrderList = [Select Id,Name,WBS_2__c,WBS_2_Order__c FROM WBS_2_Order__c]; 
    for(Site_Progress_Monitoring__c spm: trigger.new){
        for(WBS_2_Order__c wb2Order: wbs2OrderList){
            if(spm.WBS_2__c == wb2Order.WBS_2__c)
                spm.WBS_2_Order__c = wb2Order.WBS_2_Order__c;




Using map for this won't make any change in the number of scrip statements.

The only way to reduce number of script statements is to reduce the looping of the inner FOR loop,


For that you need to restrict the query results.


Try using WHERE clause if you have some condition to meet.



Rohit R


Hi Manish,


Try this...


trigger SPMUpdateWBS2Order on Site_Progress_Monitoring__c (before insert,before update) {

    Map<Id,WBS_2_Order__c> wbs2OrderMap = new Map<Id,WBS_2_Order__c>([Select Id,Name,WBS_2__c,WBS_2_Order__c FROM WBS_2_Order__c]);
    for(Site_Progress_Monitoring__c spm: trigger.new){
        spm.WBS_2_Order__c = wbs2OrderMap.get(spm.WBS_2__c).WBS_2_Order__c;



I got the below error


Error:Apex trigger SPMUpdateWBS2Order caused an unexpected exception, contact your administrator: SPMUpdateWBS2Order: execution of BeforeUpdate caused by: System.StringException: Invalid id: FDN: External entry point
I think the error is in this line
In the map, the keys are Ids. And spm.WBS_2__c is a string.
FDN is the wbs 2 value in the record.
WBS_2__c field is a string
WBS_2_Order__c is integer.

Aren't WBS_2_Order__c and SPM related via lookup?

Unfortunately no, they aren't related!


How to reduce the no of soql queries in this another simple trigger?


for(Credit_Request__c CR:Trigger.new){

    if(Trigger.isAfter && Trigger.isUpdate){
    Credit_Request__c oldCR = Trigger.oldMap.get(CR.ID);
        if (CR.Approved__c!= oldCR.Approved__c && CR.Approved__c==True) {

        List<Account> ListAcc =  [Select Id,Last_Approved_Date__c FROM Account WHERE Id=:CR.Customer_Name__c LIMIT 1];
            ListAcc[0].Last_Approved_Date__c = CR.Approved_Date__c;
            ListAcc[0].Last_Approved_Details_Reference_Name__c = CR.Name;            
            update ListAcc[0];

Please help!


Thanks much.