Hi experts i want to write a trigger using before insert on account object if we are insert 100 account records if the account is having the same name as existing account it should skipped and remaining 99 should be saved in the database
I'm afraid you can't do that selection on before insert trigger. All records will get inserted regardless, unless you have a validation rule etc.
The solution would be to do delete the accounts that have a duplicate name in the system but after they're inserted, something like this:
trigger Account on Account (after insert)
{
Set <String> accountNamesInTrigger = new List <String> ();
List <Account> accountsToDelete = new List <Account> ();
for (Account account : trigger.new)
{
accountNamesInTrigger.add(account.Name);
}
for (Account existingAccount : [SELECT Id FROM Account WHERE Name IN :accountNamesInTrigger AND Id NOT IN :trigger.newMap.keySet()])
{
accountsToDelete.add(existingAccount);
}
delete accountsToDelete;
}
I haven't compiled or tested this but with some minor tweaks or typo fixed you should be able to get it going.
You can try below code from the post https://developer.salesforce.com/forums/ForumsMain?id=906F00000008zMpIAI
trigger AvoidDuplicateAccounts on Account (before insert) {
Set<String> setAccountName = new Set<String>();
for (Account objAccount: [Select Name from Account])
setAccountName.add(objAccount.Name);
for(Account objAccount: Trigger.new) {
if(!setAccountName.contains(objAccount.Name)) {
setAccountName.add(objAccount.Name);
} else {
objAccount.Name.addError('Account with same name Exists');
}
}
}
Hi Borris, i think your solution delete the existing records instead of the one which are just inserterd. also it does not prevent duplicates with in the list of new records inserted. But Raghava want the new dublicate accounts to be skipped.
The solution would be to do delete the accounts that have a duplicate name in the system but after they're inserted, something like this:
I haven't compiled or tested this but with some minor tweaks or typo fixed you should be able to get it going.
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_exceptions.htm
here is the solution preventing duplicate account name and inserting remaining accounts
trigger preventduplicate on account (before insert)
{
list<account> accountlist = new list<account>();
list<account> acclist = trigger.new;
list<account> accold = [select id, name from account];
for(account a :acclist)
{
for(account old : accold)
{
if(old.name==a.name)
{
system.debug(' duplicate account name');
break;
}
else
{
accountlist.add(a);
}
}
}
insert accountlist;
}