0

I have a batch class to update case object. When i am running this job, getting an error: Too many SOQL queries.

Can some one help me to write the 'query on feeditem' out side of the for loop in EXECUTE method.

Here is my code.

global class BatchtoUpdateBusinessDays implements Database.Batchable { Public final String Query;

    global BatchtoUpdateBusinessDays() {
        query = 'SELECT Id,Status,No_of_Days_Case_Untchd_Business_Days__c FROM Case WHERE Status != \'Closed\' or Status != \'Duplicate\' or Status != \'Deleted\'';
        } 

    global Database.QueryLocator start(Database.BatchableContext BC) {

       return Database.getQueryLocator(query);

}

global void execute(Database.BatchableContext BC, List<Case> scope) {
    list<businesshours> bh  = new List<businesshours>([select id,Name from businesshours where Name = 'Working Days']);

 for(Case c : scope)
 {

     String BusinessHours_Id = bh[0].Id;
     list<Feeditem> FIlist = new list<Feeditem> ([Select Id, CreatedDate from Feeditem where parentId = :c.Id]);
     Long  Mins_since_lastTouched = BusinessHours.diff (BusinessHours_Id, FIlist[0].CreatedDate, System.Now()) / 1000 / 60;
     System.debug('<<<<>>>>'+ Mins_since_lastTouched );
     c.No_of_Days_Case_Untchd_Business_Days__c = Mins_since_lastTouched / 24 / 60;
     System.debug('<<<<>>>>'+ c.No_of_Days_Case_Untchd_Business_Days__c );
 }
 update scope;

}

global void finish(Database.BatchableContext BC) {

} }

3
  • Avoid SOQL Queries or DML statements inside FOR Loops
    – S B
    Nov 9, 2016 at 12:11
  • Can you please help out here, to write the logic outside of for loop. Since i am facing errors when accessing the values of the query.
    – venky
    Nov 9, 2016 at 12:13
  • You should really write this functionality as a trigger on FeedItem.
    – Adrian Larson
    Nov 9, 2016 at 12:27

1 Answer 1

0

Here is sample code to take out of soql from for loop.

//Case Id List
List<Id> caseIdList = new List<Id>();
for(Case temp : scope) {
    caseIdList(temp.id);
}
//Feed Item List
List<Feeditem> feedList = [select id,Parentid,....from FeedItem Where Parentid in :caseIdList];
Map<Id,FeedItem> caseIdFeedMap = new Map<Id,FeedItem>();
for(FeedItem item : feedList) {
caseIdFeedMap.put(item.ParentId,item);
}


for(Case temp : scope) {
//your logic
if(caseIdFeedMap.containsKey(temp.id)) {
    caseIdFeedMap.get(temp.id);
}
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .