-1

I have simple requirement to insert number of Accounts. Now what I noticed to call the following I have to pass SOQL which is irrelevant since there will be no use of the result of this query

Please suggest how can I call batch apex without passing SOQL.

Database.executeBatch(new BatchAccountsProcess('Select id from Account limit 1'));

 global class BatchAccountsProcess .... {

  global BatchAccountsProcess(String qryStr)
 {
     Query = qryStr;
 } 

 global Database.QueryLocator start(Database.BatchableContext BC)
 {
     return Database.getQueryLocator(query);
 }
 global void execute(Database.BatchableContext BC,List<sObject> scope)
 {
       for(integer iAcc = 0 ;iAcc < 5000 ; iAcc++) {
        Account accObj =  new Account(name='Arijit_batch_'+iAcc);
        lstAccount.add(accObj);
    }         
      Database.insert(lstAccount);
  }

}

2

1 Answer 1

1

You can create a number of records like so:

public class CreateAccountsBatch implements Database.Batchable<Account>, Iterable<Account>, Iterator<Account> {
    Integer counter = 0, max;
    // How high to count to
    public CreateAccountsBatch(Integer max) {
        this.max = max;
    }
    // Iterator to use
    public Iterator<Account> iterator() {
        return this;
    }
    // Get next account record in iterator
    public Account next() {
        return new Account(Name='Arijit_batch_'+counter++);
    }
    // Any more accounts to do
    public Boolean hasNext() {
        return counter < max;
    }
    // Database.Batchable start method
    public Iterable<Account> start(Database.BatchableContext context) {
        return this;
    }
    // Database.Batchable execute method
    public void execute(Database.BatchableContext context, Account[] scope) {
        insert scope;
    }
    // Database.Batchable finish method
    public void finish(Database.BatchableContext context) {

    }
}

Which you can then call as:

Database.executeBatch(new CreateAccountsBatch(5000));
6
  • Many thanks .. Will check this . Be safe May 12, 2020 at 18:26
  • One quick thing If I need to add more than 5M records by this apex , how can I achieve that May 12, 2020 at 18:42
  • I would suggest you do that with a bulk dataload instead of a batch May 12, 2020 at 18:54
  • @ArijitNagChowdhury This supports up to 50m rows in theory. But I agree with Sergio, if you have need for this much data, consider a data loader upload instead.
    – sfdcfox
    May 12, 2020 at 19:07
  • 1
    @ArijitNagChowdhury You'll be limited by heap size way before you can process millions of records of a CSV. Use another technology, such as a Lightning Component, Bulk API, Data Loader, or something else.
    – sfdcfox
    May 12, 2020 at 19:12

Not the answer you're looking for? Browse other questions tagged .