Fetch all the records from Object And Hard Delete the records using Batch Apex

By | January 10, 2020

Hi, here we have shown, how to Fetch all the records from Custom Object And Hard Delete the records(Hard Delete means delete from Recycle bin Also) using Batch Apex.

Apex Controller

Global class Building _Delete implements Database.Batchable<Sobject>{
    Global Database.QueryLocator start(Database.BatchableContext bc){
        string query='select id from Building__c';
        return Database.getQueryLocator(query);
    }
    Global void execute(Database.BatchableContext bc,List<Building__c>scope){
        delete scope;
        Database.emptyRecycleBin(scope);
    }
    Global void Finish(Database.BatchableContext bc){
        messaging.SingleEmailMessage mail = new messaging.SingleEmailMessage();
        string[] toadd = new string []{'[email protected]'} ;//our own mail 
        mail.setToAddresses(toadd);
        mail.setSubject('Batch Completion Alert');
        mail.setPlainTextBody('BatchJob'+bc.getJobId()+'is Processed Successfully');
        messaging.Email[] emails = new messaging.Email[]{mail};
            messaging.sendEmail(emails);
        
    }
}

Output

For this output, open debug anonymous window and write below code

Building _Delete bd = new Building _Delete ();

Database.executeBatch(bd);

Leave a Reply

Your email address will not be published. Required fields are marked *