0

I am a beginner developer and need help. I want to update the field value of the account based on the account history field value(Resigned date) - therefore, I have to get the value of the field from account history that has been entered for the first time - which requires me to filter the oldvalue is equal to null. I need to get this done only for certain accounts which has a field Named/called Status with the value/picklist "Former Member". I have written some code but I am getting 101 error because I have a query in loop. Thanks in advance for the help. Below is my code

for(account acc : [select id from account where status__c = 'former member']){    
        for(AccountHistory ah:[SELECT AccountId, field,createddate, NewValue,OldValue FROM AccountHistory where accountid =:acc.id and

(field ='status_C' or field ='Date_Resigned_c') ]) {
if((ah.oldvalue == Null) || (ah.field=='date_resigned')){
System.debug('AccountID = '+ah.accountid+' '+ 'Created date =' +ah.createddate +', '+ 'Field name

change ='+' ' + ah.Field +', '+ 'New value ='+' ' + ah.NewValue+', ' + 'Old value ='+' ' + ah.OldValue);
            }
        }  
}

I know that the second For loop is causing the error because I am iterating one record at a time.

0

Change your query to

 [SELECT Field, CreatedDate, NewValue, OldValue, Account.Status__c
   FROM AccountHistory
   WHERE Account.Status__c = 'former_member' AND
        Field IN ('Status__c','Date_Resigned__c')]

and you'll avoid the inner loop

  • was able to have only one loop as advised, however I am getting the below error now. System.LimitException:Too Many Query row:50001. Thank you for help – Megnath Oct 16 at 1:21
  • @rameshpm That just means you need to filter your query further. If you do need that amount of records to be processed, it should be done in a batch class. – Drew Kennedy Oct 16 at 1:40
  • Thank you.. Now I can learn batch class :) – Megnath Oct 16 at 1:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.