Hello friends, In this post i will show you, how we can pass parameters to batch apex class. This is very useful when you have execute batch on parameter based records.

Passing parameter to batch apex

Here, I will provide two examples that helps you to pass parameter in batch apex.

1. Using Class Constructor

 global class BatchWithParameter implements Database.batchable<sObject>, Database.Stateful{
global boolean runInTestMode = false;
global SET<string> accountId;

global BatchWithParameter(boolean runInTestMode,SET<string> accountId) {
this.runInTestMode = runInTestMode;
this.accountId=accountId;
}

global Database.QueryLocator start(Database.BatchableContext BC) {
String queryString = 'Select Id, Name From Account Where Type != null and Id IN :accountId';
if (!runInTestMode) {
return Database.getQueryLocator(queryString);
} else {
return Database.getQueryLocator(queryString + ' Limit 10');
}
}

global void execute(Database.BatchableContext BC, List<sObject> scope) {
for(Account o : (List<Account>)scope) {
//dosomething
}
}

global void finish(Database.BatchableContext BC) {
}
}
Execution:
 //replace with your org account id
BatchWithParameter objbatch = new BatchWithParameter(false,new SET<string>{'0010K00001sVwOT'});
Database.executeBatch(objbatch, 50);
2. Using Class Variable
 global class BatchWithParameter implements Database.batchable<sObject>, Database.Stateful{
global boolean runInTestMode = false;
global SET<string> accountId;

global Database.QueryLocator start(Database.BatchableContext BC) {
String queryString = 'Select Id, Name From Account Where Type != null and Id IN :accountId';
if (!runInTestMode) {
return Database.getQueryLocator(queryString);
} else {
return Database.getQueryLocator(queryString + ' Limit 10');
}
}

global void execute(Database.BatchableContext BC, List<sObject> scope) {
for(Account o : (List<Account>)scope) {
//dosomething
}
}

global void finish(Database.BatchableContext BC) {
}
}
Execution:
 BatchWithParameter objbatch = new BatchWithParameter();
objbatch.runInTestMode = false;
objbatch.accountId = new SET<string>{'0010K00001sVwOT'};//replace with your org account id
Database.executeBatch(objbatch, 50);

Output:

Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.