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
Achilles21Achilles21 

Batch Apex : Records not being affected by code

Hi All,

 

I've two Objects Products and Details. I m trying to fetch values of the fields NAME and QUANTITY from Products .. match the product name with Details and accordingly update or insert into Details !! 

 

The problem is while executing Batch Apex Job , I m not being able to insert or update records in Details Object.

Following is the code .. Please let me know if you find the mistake .. 

 

global class taskNew implements Database.Batchable<sObject>
{
global Integer quant;
global String prod;

List<Detail__C> Det = new List<Detail__C>();

global taskNew()
{
List<Product__c> Q = [SELECT Quantity__c,Name from Product__c];

for(Product__c p:Q)
{
    quant= (Integer)p.Quantity__c;
    prod = (String)p.Name;
}
}

global Database.QueryLocator start(Database.BatchableContext BC)
{
return Database.getQueryLocator([SELECT sum_of_item__c,prod_name__c from Detail__c]);
}

global void execute(Database.BatchableContext BC, List<Detail__c> scope){
    // for(integer i=0;i<2;i++){
     for(Detail__c s : scope){
     if(s.prod_name__c==prod)
     {
        s.sum_of_item__c+=quant;
        update scope;
     }
     else
     {  
     Detail__c d = new Detail__c();
     d.prod_name__c = 'Test';
     d.sum_of_item__c = quant;
     det.add(d);
     insert det; 
     }
      
     }
     }
     
global void finish(Database.BatchableContext BC){} 

}

 

Mohith Kumar ShrivastavaMohith Kumar Shrivastava

1)First of all i am seeing you are making a DML inside For loop.Please avoid this .The code under execution method also have governor limits applied .

 

2)Why are you querying constructor and according to your logic only the last values of Products name  and Quantities will be considered .

 

So please rethink on the logic and dont query without where clause and it can easily hit governor limits .

 

How are your Product__c and Detail__c related ?