+ Start a Discussion
lakshmiNarasimha ReddylakshmiNarasimha Reddy 

how to insert multiple records using dynamic apex in salesforce

how to insert multiple records using dynamic apex in salesforce
Himanshu ParasharHimanshu Parashar

What do you mean by dynamic apex ?
giri rockzzzzgiri rockzzzz
List<Account> accList;
Use Database.Insert(accList, false);
sandeep sankhlasandeep sankhla
Hi Lakshmi,

You can simply collect all the records in list and then you can insert all of them at a time..


List<Contact> lstContact = new list<Contact>();

for(Account objAcc: lstAccounts)
    Contact objContact = new Contact(LastName = 'test', AccountId = objAcc.Id);
     lstContact.add(objContact );


   insert lstContact ;

In above example I have one Account list which will copntain 10 account records now I need to create 10 contact for these accounts and associate them with accopunt...

SO I am iterating the accounts and createing contact for each and storing all contacts in a list and then I am inserting all of them..

Please check and let me know if this is what you wanted ti know, how to use collections and do DML..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Salesforce Certified Developer 

Muhammad Saad JavedMuhammad Saad Javed
Hey , 
you can add multiple records lets say 100 in one statement by following sample code

List<Apex_Customer__c> custList = new List<Apex_Customer__c>();
for(integer i=1; i<100; i++)
    Apex_Customer__c objCust = new Apex_Customer__c();
    objCust.name='Muhammad Saad Javed'+i;
    objCust.Apex_Active__c = true ;
    objCust.Apex_Customers_Description__c = 'This Customer is Added by Statement';
    objCust.Apex_Customer_Status__c = 'Inactive';
    objCust.Email__c ='Cust'+i+'@email.com';
insert custList;

you have to coppy this code in execute anonymouse window and change object names as per your Developer edition and execute, 100 records will be added :) 
Alper OzdamarAlper Ozdamar
I have a question why "insert custList;" takes to much time like 8000 milliseconds.