You need to sign in to do that
Don't have an account?
SaiVineeth Maddula
Batch Class to delete opps whose closedate is last month
Hi, I am trying to write a batch class which will delete the opportunities whose CloseDate is last month and update checkbox in related account.
//Batch Class
global class DeleteOppsBatch implements Database.Batchable<SObject> {
List<Account> newList = new List<Account>();
global Database.QueryLocator start (Database.BatchableContext BC) {
return Database.getQueryLocator([Select Id, DeletedOpp__c, (SELECT Id, CloseDate FROM Opportunities WHERE CloseDate = LAST_N_DAYS:30) FROM Account]);
}
global void execute(Database.BatchableContext BC, List<Account> accList) {
for(Account acc : accList) {
acc.DeletedOpp__c = TRUE;
newList.add(acc);
}
//update newList;
}
global void finish(Database.BatchableContext BC) {
System.debug('listsize:'+newList.size());
delete newList;
}
}
I didn't understand why this class is not working. Can someone help me achieve this functionality.
Thanks in advance.
//Batch Class
global class DeleteOppsBatch implements Database.Batchable<SObject> {
List<Account> newList = new List<Account>();
global Database.QueryLocator start (Database.BatchableContext BC) {
return Database.getQueryLocator([Select Id, DeletedOpp__c, (SELECT Id, CloseDate FROM Opportunities WHERE CloseDate = LAST_N_DAYS:30) FROM Account]);
}
global void execute(Database.BatchableContext BC, List<Account> accList) {
for(Account acc : accList) {
acc.DeletedOpp__c = TRUE;
newList.add(acc);
}
//update newList;
}
global void finish(Database.BatchableContext BC) {
System.debug('listsize:'+newList.size());
delete newList;
}
}
I didn't understand why this class is not working. Can someone help me achieve this functionality.
Thanks in advance.
try Below code
All Answers
Global class DeleteOppsBatch implements Database.Batchable<SObject> {
global Database.QueryLocator start (Database.BatchableContext BC) {
return Database.getQueryLocator([Select Id, DeletedOpp__c, (SELECT Id, CloseDate FROM Opportunities WHERE CloseDate < LAST_N_DAYS:30) FROM Account]); //it should be using < mark as you want closedate older than 30 days.
}
global void execute(Database.BatchableContext BC, List<Account> accList) {
List<Account> updateAccounts = new List<Account>();
List<Opportunity> deleteOpps = new List<Opportunity>();
for(Account acc : accList) {
if(acc.Opportunities.size() > 0)
{
deleteOpps.addall(acc.Opportunities);
acc.DeletedOpp__c = TRUE;
updateAccounts.add(acc);
}
}
if (updateAccounts.size() > 0) {
Delete deleteOpps;
Update updateAccounts;
}
}
global void finish(Database.BatchableContext BC) {
System.debug('listsize:'+newList.size());
}
}
try Below code
Thanks for your response. Now I was able to run the batch class.