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
R557R557 

How to insert contacts against each of 100 pre-existing Accounts in a newly created org. [Note - This is a one time activity.]

Best Answer chosen by R557
Ajay K DubediAjay K Dubedi
Hi Rahul,

Try the following apex class:

integer i = 0;
List<Contact> conlist = new List<Contact>();
List<Account> acclist = [SELECT Id FROM Account LIMIT 100];
for(Account a : acclist){
    Contact c = new Contact();
    c.LastName = 'ContactName'+i;
    c.AccountId = a.Id;
    conlist.add(c);
    i++;
}
insert conlist; 

Here I'm assuming you have to insert one Contact per Account if you want more you have to use one more for loop inside the current loop.

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi

All Answers

Ajay K DubediAjay K Dubedi
Hi Rahul,

Try the following apex class:

integer i = 0;
List<Contact> conlist = new List<Contact>();
List<Account> acclist = [SELECT Id FROM Account LIMIT 100];
for(Account a : acclist){
    Contact c = new Contact();
    c.LastName = 'ContactName'+i;
    c.AccountId = a.Id;
    conlist.add(c);
    i++;
}
insert conlist; 

Here I'm assuming you have to insert one Contact per Account if you want more you have to use one more for loop inside the current loop.

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks,
Ajay Dubedi
This was selected as the best answer
R557R557
Thanks Ajay.