Script to delete multiple records using Apex salesforce


Delete multiple records from salesforce anonymous block using some script.find the below script just paste the script in the anonymous vlock and select the code and click on Execute Highlighted.

Before that if any conditions need to check add it in SOQL Query or if condition then it will filter the records and delete the records.

If there are more records we have to run this script multiple times .if we try to delete all the records at a time we might get the DML and limit exceptions.so adding limit in SOQL query and executing.

Example : 

Object : ABC__c
Fields : field1__c, field2__c

list<ABC__c> abclist = new list<ABC__c>();
List<ABC__c > alltldroles = [SELECT id,name,field1__c,field2__c
                             FROM ABC__c LIMIT 1000];
if(alltldroles.size()>0){
    for(ABC__c tldroleslist : alltldroles) {
         if(tldroleslist.field1__c != null && tldroleslist.field2__c!=null )  {
          abclist.add(tldroleslist);
      }
}
}
try{
    if(abclist.size()>0){
    Delete abclist; 
    }
}
catch (Exception e) {
    System.debug('The following exception has occurred: ' + e.getMessage());
}

Exception handling using try and catch.

Comments

  1. Hey,
    I just built a Library to delete bulk records in apex.
    You can delete them in user or system mode in a batch size that suits you.
    There are a host of other features too.
    To use the library you can go to : https://github.com/vipul-goyal/Salesforce-Batch-To-Delete-Records
    The code is in DX format.

    Please star the repository if you find it worth it.

    Thanks  

    ReplyDelete
  2. Casinos in Malta - Filmfile Europe
    Find the best Casinos in Malta aprcasino including bonuses, games, 바카라 사이트 games and the history of filmfileeurope.com games. We https://deccasino.com/review/merit-casino/ cover all the main reasons to ventureberg.com/ visit Casinos in

    ReplyDelete

Post a Comment

Popular posts from this blog

Community/Experience Cloud Interview Questions

Change Owner / Update record using Lightning Custom Button Salesforce