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
Admin ProcessAdmin Process 

run trigger issue - Too many SOQL queries: 101

Hi forum,

I need you help, I have a trigger when  I run it send the following message error:
"System.LimitException: Too many SOQL queries: 101"
this is the code:

It is necessary that the product codes that are in the SAF266ORDOOpenOrders _ C object  that in the Product2 object in SAPDELETED _ c = ' 0 ' field, in the Product object must pass SAPDELETED _ c = ' 1 '



trigger SAF266ORDOOpenOrders_tgr on SAF266ORDOOpenOrders__c (after insert, after update) {

 if (Trigger.isAfter){

 for (SAF266ORDOOpenOrders__c a : Trigger.New)
         {
             List<Product2> GetProdInactive = [SELECT id, CODESKU__c, SAPDELETED__c  FROM Product2 WHERE CODESKU__c =  :a.PRODCODEO__c and SAPDELETED__c  = '0' ];
             
             for(Product2 prodActive : GetProdInactive)
                {
                  prodActive.SAPDELETED__c = '1';
                }
                update GetProdInactive;    
              
         }

]


Please help to check and modify it. Thanks in advance.

Regards.
Navin Selvaraj23Navin Selvaraj23
Hey Admin,

You should not use SOQL query inside the for loop. That will be not the right one to do so. 
To fix the issue, Avoid SOQL queries that are inside FOR loops., change your code so that the number of SOQL fired is less than 100 in a single call.

Please try the below code: It might help you.
if (Trigger.isAfter){
    List<String> codeskuList = new List<String>();
    List<String> sapDeletedList = new List<String>();
    for (SAF266ORDOOpenOrders__c a : Trigger.New)
    {
        
        codeskuList.add(a.PRODCODEO__c);
    }
    List<Product2> GetProdInactive = [SELECT id, CODESKU__c, SAPDELETED__c  FROM Product2 WHERE CODESKU__c in: codeskuList and SAPDELETED__c  = '0' ];
    
    for(Product2 prodActive : GetProdInactive)
    {
        prodActive.SAPDELETED__c = '1';
    }
    update GetProdInactive;    
}
If it helps, mark it as the best answer and solved, So it might help others.


Regards,
Navin

 
Admin ProcessAdmin Process
Hi Navin,

Thanks in advance for you help.

I'm begginer in apex code and I have done several tests and works well with few records to load but when I make a load of more than 1000 records is too slow, is there any other way to optimize the time?