You need to sign in to do that
Don't have an account?
trigger problem: System.LimitException: Too many SOQL queries: 101
trigger AccountCreateTrigger on Account (before insert, before update) {
for (Account acc: Trigger.new)
{Account [] accs = [SELECT Name FROM Account WHERE Name = :acc.Name LIMIT 1];
if (accs.size() > 0 ) //if account already exists, block and show the information on the page
{acc.addError('Account \'' + accs[0].Name + '\' already exists. Please use existing account or contact your Salesforce Administrator for assistance.'); }
}
}
This has the feel of an easy code but being new to visualforce and apex, I can't seem to figure out how to get past this error. Hope you can help, thanks!
There is a limit of 100 SOQL queries.
I understand that you are trying to check if an account of the same name exists.
Try to think of ways to write a single query out of the loop to fetch the required data.
Regards,
Satish Kumar
try this,
Thanks,i tried the code dapanchal and it still got the same error while pointing to line 3 (confused why it pointed there).
Maybe I should elaborate:
I created a data loader program that allows a user to upload an excel (csv) file and thus efficiently add contacts into salesforce in one go. I've already put in duplicate checks and made it so that the program takes everything it needs in one select statement so that it wouldn't have to be spammed in a loop. The problem is this trigger, I can't think of a way to do the same to the trigger since a new instance of it is created every (before insert, before update) right? Should I just deactivate the trigger? Or is there a way to avoid the SOQL error?
Really appreciate the help guys thanks!
Set<ID> setAccountId = new Set<ID>();
Set<String> setAccountName = new Set<String>();
if(Trigger.isUpdate){
for(Account acc:Trigger.New){
setAccountName.add(acc.Name);
setAccountId.add(acc.Id);
}
}
}
if(setAccountName.size()>0){
List<Account> lstAccount = new List<Account();
if(Trigger.IsUpdate){
lstAccount = [Select Id, Name From Account Where Name in:setAccountName and Id Not In:setAccountId];
}
else{
lstAccount = [Select Id, Name From Account Where Name in:setAccountName];
}
Map<String, Account> mapExisting = new Map<String, Account>();
if(lstAccount.size()>0){
for(Account acc:lstAccount){
mapExisting.put(acc.Name, acc);
}
for (Account acc: Trigger.new){
if(mapExisting.containsKey(acc.Name) == true){
acc.addError('Account \'' + acc.Name + '\' already exists. Please use existing account or contact your Salesforce Administrator for assistance.');
}
}
}
}
}