Search code examples
triggersapexdml

DML statement to add multiple accounts in single step


I want to add multiple accounts to the salesforce object from the anonymous window. I know how to do that using the below code

 Account acc = new Account(Name='account1');
 List<Account> accToAdd = new List<Account>();
 accToAdd.add(acc);
 insert accToAdd;

but when I am trying to insert multiple accounts(see code below), it is giving me error as "Line: 1, Column: 5 Unexpected token '<'."

List<Account> accToAdd = new List<Account>(
 { new Account(Name='triggertest4'),
   new Account(Name='triggertest5'),
   new Account(Name='triggertest3')
 });

insert accToAdd;

can anyone help???


Solution

  • You should use only brackets in the latter case:

    List<Account> accToAdd = new List<Account> {
       new Account(Name='triggertest4'),
       new Account(Name='triggertest5'),
       new Account(Name='triggertest3')
    };
    System.debug(accToAdd);
    
    insert accToAdd;
    

    You could also create an empty list, then add the elements, which could be useful in a for-loop:

    List<Account> accToAdd = new List<Account>();
    for (Integer i=3; i<6; i++) {
        accToAdd.add( new Account(Name='triggertest' + i) );
    }
    System.debug(accToAdd); // |DEBUG|(Account:{Name=triggertest3}, Account:{Name=triggertest4}, Account:{Name=triggertest5})
    
    insert accToAdd;