Apex bulk coding style to update a field from a list of queried records

Glancing at your code, I can tell it won't compile. You are trying to update a variable that does NOT exist at that point.

 for(invoice_statement__c inn : inv)
           inn.status__C = 'pending';
      update inn;

Your variable inn has already died by that point.

for(invoice_statement__c inn : inv)
{
  inn.status__C = 'pending';
}
update inv;

You should really be using update inv; instead. You should be setting the value and then updating all of the records at once instead of 1 at a time.

for(invoice_statement__c inn : inv)
{
   inn.status__C = 'pending';
   update inn;//DO NOT DO THIS
}

This would compile, but don't do it this way. You will hit governor limits when there are multiple records because you have a limited number of DML statements you can execute within a single iteration of code. Doing DML inside a loop will cause that to happen.


In addition to dphil's corrections, you could also perform this logic by simply creating a workflow rule of whenever an Invoice Statement is created/updated to Open status, then peform a workflow field update to set the status to 'Pending'.

Tags:

Soql

Apex