function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Avinash AngasayAvinash Angasay 

related with dml

Q->  Insert 100 student’s records. Rollback all the inserted records if the number of successful insertion is less than 80
Best Answer chosen by Avinash Angasay
mukesh guptamukesh gupta
Hi Avinash,

Please follow below code, it's not tested So please try it
 
Savepoint sp = Database.setSavepoint();;

List<Account> accList = new List<Account>();
for(Integer i = 0; i<100; i++){
   Account a = new Account(); 
           a.Name='a'+i; 
           a.AccountNumber = i;
  accList.add(a);
}

Database.SaveResult[] saveResultList = Database.insert(accList, false); 
Integer count = 0;
for (Database.SaveResult sr : saveResultList) {
    if (sr.isSuccess()) {
       count++;
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors                
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}

if(count < 80){
   Database.RollBack(sp);
}


if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh

All Answers

mukesh guptamukesh gupta
Hi Avinash,

Please follow below code, it's not tested So please try it
 
Savepoint sp = Database.setSavepoint();;

List<Account> accList = new List<Account>();
for(Integer i = 0; i<100; i++){
   Account a = new Account(); 
           a.Name='a'+i; 
           a.AccountNumber = i;
  accList.add(a);
}

Database.SaveResult[] saveResultList = Database.insert(accList, false); 
Integer count = 0;
for (Database.SaveResult sr : saveResultList) {
    if (sr.isSuccess()) {
       count++;
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors                
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}

if(count < 80){
   Database.RollBack(sp);
}


if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh
This was selected as the best answer
SwethaSwetha (Salesforce Developers) 
HI Avinash,

Apex gives you the ability to generate a savepoint in a scenario like yours, that is, a point in the request that specifies the state of the database at that time. Any DML statement that occurs after the savepoint can be discarded, and the database can be restored to the same condition it was in at the time you generated the savepoint.

See official doc: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_transaction_control.htm

Sample code that you could customize as per your need:
Savepoint sp = Database.setSavepoint();
try{
    // DML statements here
    insert opps;
    insert quotes;
    insert quoteItems;
}catch(Exception e){
    // An exception was caught. We need to revert back to our Savepoint
    // This will rollback all successful changes. So, if opps saved successfully
    // and then quotes failed, the opps will be rolled back as well
    Database.rollback(sp);

    // Add the error to the page for the user to see
    ApexPages.addMessages(e);
}
Reference: https://salesforce.stackexchange.com/questions/9410/rolling-back-dml-operation-in-apex-method

If this information helps, please mark the answer as best. Thank you