+ Start a Discussion
Chidanand Magadum 24Chidanand Magadum 24 

Ho to check the Duplicacy of record before inserting it.

Hi Guyz,
I am creating an opportunity whose name is same as that of the Account based on the criteria.
Now After creating an opportunity,Again when we run the script it should not create another opportunity if the opportunity name whose name which is same as that of the account name is found.

How to Proceed further to achieve this.
Here is My code.

Date  d = Date.Today();
List<Account> AllAccounts= new List<Account>([select id,Name,ARR__c,Relationship_Start_Date__c,
                                              (Select Id,Account.Id from Opportunities) from Account]);
                                              

for(Account a:AllAccounts)
{
    
    Integer numberDaysDue= a.Relationship_Start_Date__c.daysBetween(d);
    if(numberDaysDue<=60){
       
        Opportunity O= new Opportunity();
        o.Name=a.Name;
        o.StageName='Legal';
        o.Amount=a.ARR__c;
        o.AccountId=a.ID;
        o.CloseDate=Date.today();
        o.NextStep='Won';
        system.debug('Account Id'+o.AccountId);
        insert o;
      
    }
}
Yogesh KulkarniYogesh Kulkarni
Hi Chidanand,

The opportunity name should be according to business process rather than code. Please check on this also if you dont want same name opp then put a validation rule rather then putting some code.

Thanks,
Yogesh
Waqar Hussain SFWaqar Hussain SF
Date  d = Date.Today();
List<Account> AllAccounts= [select id,Name,ARR__c,Relationship_Start_Date__c,
                           (Select Id,Account.Id from Opportunities) from Account];
List<Opportunity> RecordstoInsert = new List<Opportunity>();
set<String> RecordsToAvoid = new Set<String>();

for(Account a:AllAccounts)
{
    
    Integer numberDaysDue = a.Relationship_Start_Date__c.daysBetween(d);
    if(numberDaysDue<=60){
        Opportunity O= new Opportunity();
        o.Name=a.Name;
        o.StageName='Legal';
        o.Amount=a.ARR__c;
        o.AccountId=a.ID;
        o.CloseDate=Date.today();
        o.NextStep='Won';
        system.debug('Account Id'+o.AccountId);
        
    
	if(RecordsToAvoid.add(o.Name))  {
            	RecordstoInsert.add(o);
            }

		insert RecordstoInsert;
	}
}