Delete records across multiple objects using Apex in Salesforce

Sample Code:

  1. List < Id > toDeleteIds = new List < Id > { '0WO2M000000mbwnWAA',  
  2. '5002M00000mnEdCQAU',  
  3. '0WO2M000000qewsWAA',  
  4. 'a0k2M000066AYgKQAW'};  
  5.   
  6.   
  7. Database.DeleteResult[] deleteResults = Database.delete( toDeleteIds, true );  
  8. for ( Database.DeleteResult dr : deleteResults ) {     
  9.                 
  10.     if ( !dr.isSuccess() ) {  

  11.         for ( Database.Error err : dr.getErrors() ) {  

  12.             System.debug(LoggingLevel.Error, 'The following error has occurred.'  
  13.                 + '\n' + err.getStatusCode() + ': ' + err.getMessage()  
  14.                 + '\n fields that affected this error: ' + err.getFields());  

  15.         }  

  16.     }  

  17. }  

Note:
Don't include child record ids and master records ids if they are strongly coupled( Master Detail Relationship ).

No comments:

Post a Comment