+ Start a Discussion
SFDC 2017SFDC 2017 

Want to know about dynamic Apex code to be used in Batch Apex

Hi All,  I used batch Apex normally but using dynamic apex i am new.Can anyone please guide me for the Following Scenario using Batch Apex(Dynamic)
 In Batch Class constructor: global Account batch(String ObjectName)  
My scenario i passed this ObjectName as parameter and
if (ObjectName==Account)
{ need to query account  records
}
else if (ObjectName =Contact )
{ Query Contact records)
}
So i will get either account or contact records in scope and in execute method i will create records for other custom object based on this scope And in scheduler class how i will pass for account and contact  
Please anyone guide me to do this  
Thanks in advance
Santosh Sriram 2310Santosh Sriram 2310
Use the constructor pass the objectype. 
public class callNotesbatchcls {
 
    Public PageReference callingMethod()
    {
        batchNotesInsert shn = new batchNotesInsert(sObjectType);
        database.executeBatch(shn ); return null;
    }
}
 
global class batchNotesInsert implements Database.Batchable<sObject>, Database.Stateful {
 
    private String strParameter;
 
    public batchNotesInsert(String strParam) {
        strParameter = strParam;
    }
     global Database.QueryLocator start(Database.BatchableContext BC) {
         //If account
         String query ='';
         if(strParameter == 'Account')
               query = 'select id from account';
         else if(strParameter == 'Contact') //Contact
               query = 'select id from account';
 
        return Database.getQueryLocator(query);
    }
 
    global void execute(Database.BatchableContext BC, List<sObject> scope) {   
    }  
 
    global void finish(Database.BatchableContext BC) {
    }
}


If this answer helps you, please mark this as a solution to help the community get solutions; quicker.

Thanks

Santosh Kumar Sriram

SFDC 2017SFDC 2017
Thanks @ SANTOSH for your Quick Response.
Santosh Sriram 2310Santosh Sriram 2310
@Archu

If you think this helped you, please mark this as an answer!

Thanks
Santosh Kumar Sriram
SFDC 2017SFDC 2017
Hi Santosh,

One more error when running test class it is showing error as Error MessageSystem.QueryException: unexpected token: <EOF>
Stack TraceClass.ClassbatchInsert.start: line 32, column 1. return Database.getQueryLocator(query);this is 32 line.
  query = 'Select Id,CreatedDate FROM Account  WHERE CreatedById =:UserId AND Account_Id__c = NULL';
what is the problem here?