+ 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.
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
 
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