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
SAHANA GHOSHSAHANA GHOSH 

Why am I getting this error ?

public List<Account> acclist = new List<Account>();
for(integer i =0; i<10; i++){
    Account acc = new Account();
    acc.name='Account'+i;
    acc.Industry = 'Agriculture';
    acclist.add(acc);
}
Database.SaveResult[] sr= database.insert(acc,false);
for(database.SaveResult srtest : sr){
    if(srtest.isSuccess()){
        system.debug('success');
    }
    else{
        for(database.error e : srtest.getErrors()){
            system.debug('**** '+e.getMessage());
        }
    }
}


I am getting -
variable doesnt exist : acc
error while executing this in anonymous window.
Best Answer chosen by SAHANA GHOSH
SUCHARITA MONDALSUCHARITA MONDAL
Hi Sahana,

Database.SaveResult[] sr= database.insert(acc,false);  // pass acclist instead of acc.
it should be  Database.SaveResult[] sr= database.insert(acclist,false);


Thanks,
Sucharita
 

All Answers

SUCHARITA MONDALSUCHARITA MONDAL
Hi Sahana,

Database.SaveResult[] sr= database.insert(acc,false);  // pass acclist instead of acc.
it should be  Database.SaveResult[] sr= database.insert(acclist,false);


Thanks,
Sucharita
 
This was selected as the best answer
chanchal_:)chanchal_:)
Hello Sahana,

Here you have to write -- Database.SaveResult[] sr= database.insert(acclist,false);


As scope of acc was only there in for loop so we can't excess it outside. You have added all records to be created into list, and now yoi can use that list directly to insert.

so correct is - 
public List<Account> acclist = new List<Account>();
for(integer i =0; i<10; i++){
    Account acc = new Account();
    acc.name='Account'+i;
    acc.Industry = 'Agriculture';
    acclist.add(acc);
}
Database.SaveResult[] sr= database.insert(acclist,false);
for(database.SaveResult srtest : sr){
    if(srtest.isSuccess()){
        system.debug('success');
    }
    else{
        for(database.error e : srtest.getErrors()){
            system.debug('**** '+e.getMessage());
        }
    }
}

let me if it helpes.
sachinarorasfsachinarorasf
Hi  Sahana,

I have gone through your problem.
public List<Account> acclist = new List<Account>();
for(integer i =0; i<10; i++){
    Account acc = new Account();
    acc.name='Account'+i;
    acc.Industry = 'Agriculture';
    acclist.add(acc);
}
Database.SaveResult[] sr= database.insert(acclist,false);
for(database.SaveResult srtest : sr){
    if(srtest.isSuccess()){
        system.debug('success');
    }
    else{
        for(database.error e : srtest.getErrors()){
            system.debug('**** '+e.getMessage());
        }
    }
}


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

Thanks and Regards,
Sachin Arora