+ Start a Discussion
indra reddy 19indra reddy 19 

Write a batch class to delete all the accounts where billing country equal to united states of America or US or USA handle the field records also in the same batch and return the batch class to delete failed records also. Once these US records are deleted

How to write the batch apex progarm.

( Write a batch class to delete all the accounts where billing country equal to united states of America or US or USA handle the field records also in the same batch and return the batch class to delete failed records also. Once these US records are deleted )
Deepali KulshresthaDeepali Kulshrestha
Hi Indra,

I've gone through your requirement and you can see below code for reference:-->

global class deleteAccounts implements Database.Batchable<sObject>{

String query;

global deleteAccounts(String q){
    query=q;
}
global Database.QueryLocator start(Database.BatchableContext bc){
    return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext bc,List<Account> scope){
    List<Account> accList = new List<Account>();
    for(Account acc:scope){
        if(acc.BillingCountry=='USA' || acc.BillingCountry=='US')
{
        Account a = (Account)acc;
        accList.add(a);
}
    }
    delete accList;
}
global void finish(Database.BatchableContext bc){

}
}


Code written in anonymous block to invoke batch:
deleteAccounts d = new deleteAccounts('select id,BillingCountry from Account');
Database.executeBatch(d);



I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com
harsha vardhan vasa 9harsha vardhan vasa 9
Hi Indra,
PFB code for reference:

global class Batch_Accounts_CountryBased implements database.Batchable<sobject>,database.stateful{
    list<account> alist = new list<account>();
    list<account> templist = new list<account>();
    Exception[] errors = new Exception[0];
    global database.QueryLocator start(database.batchablecontext bc){
        string string1='select id,name from account';
        return database.getQueryLocator('string1');
    }
    global void execute(database.BatchableContext bc,list<account>scope){
        for(Account a: scope){
            try{
                if(a.billingcountry =='USA' || a.billingcountry =='US' || a.BillingCountry =='united states of America'){
                    alist.add(a);
                }
                templist.add(a);
                system.debug('rest of the account records which not satisfied the criteria'+templist);
            }
            catch(exception e){
                errors.add(e);
            }
            system.debug('deleted records are'+alist);
            delete alist;
        }
    }
    global void finish(database.Batchablecontext bc){}
}

Anonymus block:
Batch_Accounts_CountryBased B = new Batch_Accounts_CountryBased();
database.executebatch(B);

Regards,
Vasa Harsha vardhan.