1

I am trying to get the first 10 characters from "Patient_Name__c" field into the "Patient_Id_Help__c" field but when i run the batch class it is throwing the error as "Ending position out of bounds: 10 ". Please find my batch class below

global class DataLoad implements Database.Batchable<sObject>{
             private String query;
             private Integer recordcount = 0;
             private boolean recurssion = true;

            global Database.QueryLocator start(Database.BatchableContext BC)
        {
            query='Select id,Patient_Name__c from ZS_Reports__c';
            return Database.getQueryLocator(query);
        }

        global void execute(Database.BatchableContext bc, List<ZS_Reports__c> scope) {
            recordCount=recordCount+scope.size();
            List<ZS_Reports__c> zs=new List<ZS_Reports__c>();

       for(ZS_Reports__c z:scope)
        {
            if(z.Patient_Name__c!=null)
            {
                z.Patient_Id_Help__c=z.Patient_Name__c.substring(0,10);
                   zs.add(z); 
            }
        }
                    system.debug('Updated Records:'+zs.size());
            if(zs.size()>0)
            {
                update zs; 
            }
        }
        global void finish(Database.BatchableContext bc) 
        {

        }
    } 

Can somebody help me to solve this issue.

2
  • 1
    Well, the error talks for itself. Some patients names length are smaller than 10 characters. So the substring method fails. You have to check first if the length is bigger than 10 before calling the substring method. – Martin Lezer Oct 16 '19 at 15:44
  • the field name has less then 10 chars. Code a system.debug before the substring(0,10) and see what is the value for Patient_Name__c – m Peixoto Oct 16 '19 at 15:46
2

Use left instead:

z.Patient_Id_Help__c=z.Patient_Name__c.left(10);

It does not throw an exception if there is less than 10 characters.

Remember to check for null first, if applicable:

if(z.Patient_Name__c != null) {
    z.Patient_Id_Help__c=z.Patient_Name__c.left(10);
}

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.