I have a trigger that is running two queries on an Account update: on an User object to get the User's name and one to the Account object to check if the user is different that before the update. One of our managers is doing bulk updates to the associated accounts and is triggering a 'too many SOQL queries' error:
trigger AccountOwnerUpdate on Account (after update) {
for (Account a : Trigger.new){
if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId) {
List<Account> aId = [Select OwnerId From Account where Id = :a.Id];
List<User> oName = [Select Name from User where Id = :aId[0].OwnerId];
//Do addtl actions
}
}
}
Is there a way to improve this to avoid the error? it really seems like 2 queries shouldn't trigger a 'too many queries' error. Our manager is currently limited to updating 10 Accounts at a time.
possible improvement:
trigger AccountOwnerUpdate on Account (after update) {
Map<Id,Id> accountIdToOwnerId = new map<Id,Id>();
for (Account a : Trigger.new){
if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId) {
accountIdToOwnerId.put(a.Id, a.OwnerId);
}
}
List<User> oName = [Select Id, Name from User where Id in : accountIdToOwnerId.values()];
for (User owner : oName) {
String accountId = '';
String newOwnerName = EncodingUtil.urlEncode(owner.Name, 'UTF-8');
for(Id acctId: accountIdToOwnerId.keyset()){
if (owner.Id == accountIdToOwnerId.get(acctId)) {
accountId = acctId;
}
}
//Do addtl actions with accountId and newOwnerName Strings
}
}