0

It's just a simple question I'm having(It might sound silly but I've no idea how do I insert 40000 records).

I'm first creating 200 Accounts and also creating 200 child Opportunities for each Account. Can Someone suggest to me how do I achieve it?

I think it can be done using BatchApex but I've no idea how to code for that. Below is what I'm trying to do:
public class TestOpp {
    public static void accwithOpp(){
        List<Account> createdAccount = new List<Account>();
        List<Opportunity> createdOopp = new List<Opportunity>();
        for(Integer i=1;i<=200;i++){
            Account a = new Account(Name='TestMebyClass'+i);
            createdAccount.add(a);
        }
        insert createdAccount;
        List<Account> ParentAccIds = [SELECT Id FROM Account WHERE Id IN :createdAccount];
        for(Account a : ParentAccIds){
            for(Integer i=1;i<=200;i++){
                Opportunity op = new Opportunity(Name='TestofParentAcc'+i,
                                                StageName='Prospecting',
                                                CloseDate=System.today().addmonths(1),
                                                AccountId=a.Id);
                createdOopp.add(op);
            }
        }
        insert createdOopp;
    }
}
1
  • It should be ok to run this code, but you could hit some limits in other parts of your org, CPU and so on. Basically, batch in this case could be used to chunk the 100 accounts into 100 chunks and in each insert just the opps related to this account.
    – Damecek
    Commented Mar 8, 2022 at 7:48

1 Answer 1

1

You can create the counter values as an array and return that from the start method (this being the less commonly used variant of start):

public System.Iterable start(Database.BatchableContext jobId) {

    Integer[] counts = new Integer[] {};
    for(Integer i=1;i<=200;i++) counts.add(i);
    return counts;
}

public void execute(Database.BatchableContext jobId, Integer[] counts) {

    Account[] accs = new Acccount[] {};
    for (Integer count : counts) {
        accs.add(new Account(Name='TestMebyClass'+count));
    }
    insert accs;

    Opportunity[] accs = new Opportunity[] {};
    for(Account a : accs){
        for(Integer i=1;i<=200;i++){
            opps.add(new Opportunity(
                Name='TestofParentAcc'+i,
                StageName='Prospecting',
                CloseDate=System.today().addmonths(1),
                AccountId=a.Id
            ));
        }
    }
    insert opps;
}

public void finish(Database.BatchableContext jobId) {
}

and then use a batch size that stays within governor limits, in this case say 50.

You must log in to answer this question.

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