[SalesForce] System.LimitException: Too many DML statements

I want to mass update my account record. But I got this error when trying to deploy the code.

public class Insert_CustID_Old {

    public void insertCustId() {
        List<Account> accList = [SELECT Id, Cust_ID_SUJ__c, Cust_ID_SUJ_EBS_Old__c FROM Account WHERE Cust_ID_SUJ__c != NULL];
        for(Account acc : accList){
            Account accNew = new Account();
            accNew.Id = acc.id;
            accNew.Cust_ID_SUJ_EBS_Old__c = acc.Cust_ID_SUJ__c;
            Update accNew;
        }
    }
}

System.LimitException: Too many DML statements: 151

Best Answer

In a single transaction, we have a limit of 150 DML

so if your SOQL query returns 151 records then for loop iterate over 151 time and Update accNew; will execute 151 times means you are doing 151 time DML operation that's why this error occurred.

To resolve this issue put this record into a list and update the list ex.

List<Account> accList = [SELECT Id, Cust_ID_SUJ__c, Cust_ID_SUJ_EBS_Old__c FROM Account WHERE Cust_ID_SUJ__c != NULL];

List<Account> accListToUpdate = new List<Account>();
    for (Account acc : accList){
        Account accNew = new Account();
        accNew.Id = acc.id;
        accNew.Cust_ID_SUJ_EBS_Old__c = acc.Cust_ID_SUJ__c;
        accListToUpdate.add(accNew);
    }
update accListToUpdate; //perform update outside the loop so only single dml required. 

Another way

Since you are updating the list then you could do like this.

List<Account> accList = [SELECT Id, Cust_ID_SUJ__c, Cust_ID_SUJ_EBS_Old__c FROM Account WHERE Cust_ID_SUJ__c != NULL];

    for (Account acc : accList){
        //this will update the list only. 
        acc.Cust_ID_SUJ_EBS_Old__c = acc.Cust_ID_SUJ__c;
    }
update accList ; //perform update outside the loop so only single dml required. 
Related Topic