function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vishnu YadavalliVishnu Yadavalli 

Autonumbering records within batch class

global class LDPurchasedSV implements Database.Batchable<sObject>, Database.AllowsCallouts {
global Database.QueryLocator start(Database.BatchableContext BC) {
String query = 'SELECT Name,SV_Synced_Hidden__c,Lead_Number_Hidden__c,SV_Priority_Hidden__c,OwnerId,Days_To_SV_Hidden__c, Id FROM Lead WHERE Days_To_SV_Hidden__c <= 3 and SV_Synced_Hidden__c = FALSE';
return Database.getQueryLocator(query);
}


global void execute(Database.BatchableContext BC, List<Lead> scope) {

integer i=1;

for (Lead e : scope) {
if(e.OwnerId == '00Gi0000000iqle')
{

if(e.Days_To_SV_Hidden__c ==0)
{
e.SV_Priority_Hidden__c =1;
}
else{
if(e.Days_To_SV_Hidden__c == 1)
{
e.SV_Priority_Hidden__c =2;
}
else
{
e.SV_Priority_Hidden__c =3;
}
}
e.SV_Synced_Hidden__c = TRUE;
e.OwnerId ='00Gf0000000TIWj';
}
e.Lead_Number_Hidden__c = i;
i++;
Update scope;
}
}
global void finish(Database.BatchableContext BC) { }
}

 

 

I am trying to add a number field for all the records that come through this batch. The number should increment with every record.

Lead_Number_Hidden__c should be updated with number.

The above code is giving the same number for all the records.

 

Best Answer chosen by Admin (Salesforce Developers) 
mauro_offermannmauro_offermann

Why you don't use Autoincremente in the Name field?

Try implementing Database.StateFull and declaring your i variable as field class.
Increment your i variable inside for and assign it.
Finally perform the update scope out of for.