• Polam Vishal
  • NEWBIE
  • 0 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I have a custom Object Book3__c , In which I have the records as Below.

Name          Email__c
Book1    hh@gmail.com
Book2    hh@gmail.com

Book3    gg@gmail.com
Book4    gg@gmail.com

Book5    kk@gmail.com
Book6    kk@gmail.com
Book7    kk@gmail.com

The problem with the below code is, It deletes all the records . But I need to Keep one and delete the remaining. What Am I missing here.?
 
Global class removeDuplicateRecords implements Database.Batchable<SObject> , Database.Stateful {
    
    global Set<String> emailstring;
    
    global Database.QueryLocator start(Database.BatchableContext BC){
      return Database.getQueryLocator([Select Email__c from Book3__c where Email__c != null]);
      }
    
    global void execute(Database.BatchableContext BC , List<Book3__c> scope){
        
        Set<String> emailstring = new Set<String>();
        
      //  Map<String , Book3__c> EmailBookmap = new Map<String , Book3__c>();
        for(Book3__c s : scope){
        // EmailBookmap.put(s.Email__c , s);
            emailstring.add(s.Email__c);
            
        }  
       // system.debug(EmailBookmap);
        system.debug(emailstring);
        
        List<Book3__c> bklst = [select Email__c from Book3__c where Email__c In :emailstring ];
        
        List<Book3__c> duplicatelist = new List<Book3__c>();
        
        for(Book3__c bk : Scope){
        for(Book3__c b :bklst){
           // if(emailstring.contains(b.Email__c)){
            if(bk.email__c == b.email__c){
              duplicatelist.add(b);  
            }
            else{
             emailstring.add(bk.Email__c);   
            }
        }
        }
        
       // system.debug(EmailBookmap);
        system.debug(duplicatelist);
      delete duplicatelist;
    }
    
    global void finish(Database.BatchableContext BC){
        
    }
        

}