+ Start a Discussion
K SrikanthK Srikanth 

Find nearest record


I have a requirement to find nearest lead record for all account records, I can  find the distance and sort the disance.

But I am facing issue to query two object all records in bactch apex. Is there any best way to complete this.

Thanks in advance.
AbhinavAbhinav (Salesforce Developers) 
Hi Srikanth,

Could you please share the code or query which you have tried.

K SrikanthK Srikanth
Hi Abhinav,

Here is sample code, how  I am thinking to implement, but query in execute method will hit the limit.

global class nearestrecord implements Database.Batchable<sObject>{
 public String query = 'select id, lat,long from account where lat!= null';
global Database.QueryLocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
global void execute(Database.BatchableContext BC, List<account> scope){

List<lead> leadstocalculatedistance =  select id,lat,long from lead where lat!=null;

for(account ac : scope){
for(lead l:leadstocalculatedistance){
// logic to calcualte distance
update  updatedaccounts list
global void finish(Database.BatchableContext BC){ }