+ Start a Discussion
SFDC 2017SFDC 2017 

Check if record already exists or not if it is not then create new record

Hi All,

I have written a batch class with the below scenario.
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 means if it is account it will insert with account Id in the new custom object and if Contact contact Id in the new object .Right now it is captuirng the Id into another custom Object but the problem is whenever i am executing it is capturing the same .

So here i want to eliminate the creation of duplicates means if the Record Id(Acc or con Id already in the new custom object then it should not create new record if the record is not existing then create new record with the Acc or Con Id

My Code:
  global void execute(Database.BatchableContext BC, List<SObject> scope)
    { 
        Map<id, Custom Object> CustomMap= new Map<id,Custom Map>();
         for(Sobject obj: scope)
         {      
                Custom Object cm= new Custom Object();
                 
                 cm.Recordt_ID__c =obj.Id;
                 
                  CustomMap.put(Cm.Object_ID__c, cm);
             
          }
          if(!CustomMap.isEmpty())
        {
            Database.SaveResult[] InsertResult = Database.insert(CustomMap.values(),false);
            
        }
        
    }

So here how i will check if there is already a record with same Object Id is there then it should not insert if it is not there it should create new custom object Record.Any one please guide how to do this

Thanks in advance
Tejpal KumawatTejpal Kumawat
Hi Archu,

You need to make one more SOQL on Custom object that will give you results comparision for new records vs old records, On the basis of that condtion you can eaisly eliminate existing records.

Regards
Tej Pal Kumawat
Skype : tejpalkumawat1991

If this answers your question mark Best Answer it as solution and then hit Like!
Jim JamJim Jam
Not sure if it will work, but maybe try ...

Database.SaveResult[] InsertResult = Database.upsert(CustomMap.values(),'',false);
Simha YadavSimha Yadav
@archu,

you can use this code 

trigger xyz on Account (before insert){
List<account> ac=[select id,name form account];
for(account a:trigger.new)
{
for(account acc:ac)
{
if(acc.name ==a.name)
{
ac.adderror('you can enter duplicate record');
}
}
}
}

 
SFDC 2017SFDC 2017
Thanks @simha.I have written Batch class and it is working now.i am  not using Trigger.