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
Newbie__SalesforceNewbie__Salesforce 

How to create a configurable field to delete duplicate records based on that configurable field

I have tried to delete duplicate records based on static field names but I want to delete records based on configurable fields.

My code is
global class RemovalofDuplicateLeads implements 
    Database.Batchable<sObject>, Database.Stateful {

    global Map<String,Lead> mapString_Lead = new Map<String,Lead>();  

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(
            'SELECT Name, Email from Lead where LastModifiedDate = Today'
        );
    }

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

        List<Lead> lstduplicate = new List<Lead>();
        
        for(Lead lead : scope) {
            if(! mapString_Lead.containsKey(lead.Email)) {
                mapString_Lead.put(lead.Email , lead);
            } else {
                lstduplicate.add(lead);
            }
        }
        
        System.debug(lstduplicate);
        if(lstduplicate.size() > 0) {
            delete lstduplicate;
        }
    }
    
    global void finish(Database.BatchableContext bc) {        
   
    }
}
v varaprasadv varaprasad
Hi ,

Please try once following code : 
 
global class RemovalofDuplicateLeads implements 
    Database.Batchable<sObject>, Database.Stateful {

    global Map<String,Lead> mapString_Lead = new Map<String,Lead>();  


		global list<lead> lstOfExistingLeads = [SELECT id,Name, Email from Lead Email != null];
		if(lstOfExistingLeads.size()>0){
		 for(lead l : lstOfExistingLeads){
		   mapString_Lead.put(l.email,l);
		   }  

		}



    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator(
            'SELECT Name, Email from Lead where LastModifiedDate = Today'
        );
    }

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

        List<Lead> lstduplicate = new List<Lead>();
        
        for(Lead lead : scope) {
            if(! mapString_Lead.containsKey(lead.Email)) {
                mapString_Lead.put(lead.Email , lead);
            } else {
                lstduplicate.add(lead);
            }
        }
        
        System.debug(lstduplicate);
        if(lstduplicate.size() > 0) {
            delete lstduplicate;
        }
    }
    
    global void finish(Database.BatchableContext bc) {        
   
    }
}


Hope this helps you!

Thanks
Varaprasad
@For Support: varaprasad4sfdc@gmail.com