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
syricsyric 

Trigger Help-- Exception: Too many script statements

I'm new and learning Apex.  I'm having an issue with a trigger I wrote.  It hits the script statements govenor and causes the error "System.LimitException: Too many script statements: 200001".  It works with single updates. The error was caused when I tested it by updating 2,000 opportunity records and started after 937 were succesfully updated.

 

There are three revenue fields on Opportunity (Monthly, Prorated, Membership).  When an opportunity is updated, the trigger searchs through its products and determines which field the revenue belongs to using the product description.

 

trigger Test2 on Opportunity (before insert, before update) {

// CREATE PRODUCT LIST FOR THE OPPORTUNITIES
List<OpportunityLineItem> prodList = [select ID, OpportunityId, Description, TotalPrice from OpportunityLineItem where OpportunityId in: Trigger.new];

// DEFINE STRINGS USED TO DETERMINE TYPE OF PRODUCT
String Prorated = 'Prorated';
String Membership = 'Membership';

// LOOP THROUGH OPPORTUNITIES, RESET 3 REVENUE FIELDS TO 0
	for(Opportunity a : Trigger.new){
		a.Prorated_Total__c = 0;
		a.Membership_Total__c = 0;
		a.Monthly_Total__c = 0;

// LOOP THROUGH PRODUCT LIST TO GET REVENUE TYPE AND TOTAL FOR CURRENT OPPORTUNITY
		for(OpportunityLineItem b : prodList){

//  MAKE SURE PRODUCTS BELONG TO CURRENT OPPORTUNITY
			if(a.Id == b.OpportunityId){
// DETERMINES PRODUCT TYPE FROM DESCRIPTION AND ADDS PRICE TO THE CORRESPONDING FIELD ON THE CURRENT OPPORTUNITY
		    	     if(b.Description.contains(Prorated)){
		     	     a.Prorated_Total__c += b.TotalPrice;         
		   	     }else if(b.Description.contains (Membership)){        
			     a.Membership_Total__c += b.TotalPrice; 
		    	     }else{
		             a.Monthly_Total__c += b.TotalPrice;   
	    		     }
			}   
		}
	}
}

  After looking up the error, I'm sure the issue is with the nested loop. Everything else I tried failed and I'm struggling.  Any help is appreciated, thanks.

Best Answer chosen by Admin (Salesforce Developers) 
Hengky IlawanHengky Ilawan

Hi Syric,

 

I see that you are trying to do a roll up summary.

Why not using the builtin roll up summary function?

 

-Hengky-

All Answers

Hengky IlawanHengky Ilawan

Hi Syric,

 

I see that you are trying to do a roll up summary.

Why not using the builtin roll up summary function?

 

-Hengky-

This was selected as the best answer
syricsyric

Because I did not know that was an option or that it existed.  Once again I was making things harder than they should be.  Thank you so much.