Suppose you want to update field name ‘Status’ to ‘Active’ in multiple Sobject and there are large number of records for each Sobject. Instead of writing a batch class for each Sobject you can update multiple Sobjects like this.
Declare three variables, one for SOQL, one for field name which you want to update and one for new value of field.
Here is sample code:
String qry = 'SELECT Status__c FROM XYZ'; String field = 'Status'; String val =’Active’; Database.executeBatch(new UpdateObjectBatchClass(qry,field,val),200); global class UpdateObjectBatchClass implements Database.Batchable,Database.stateful { global final String Query; global final String Field; global String Value; public UpdateObjectBatchClass(String qry, String f,Sting val) { Query = qry ; Field = f; Value = val; } public Database.QueryLocator start(Database.BatchableContext BC) { return Database.getQueryLocator(Query); } public void execute(Database.BatchableContext BC, List scope) { for(sObject Src : scope){ Src.put(Field,Value); } update scope; } public void finish(Database.BatchableContext BC) { } }
Webner Solutions is a Software Development company focused on developing CRM apps (Salesforce, Zoho), LMS Apps (Moodle/Totara), Websites and Mobile apps. If you need Salesforce customization, App development or any other software development assistance please contact us at salesforce@webners.com