I am new to APEX Code and I am having some trouble accomplishing a task assigned to me

I am trying to execute anonymous code that will get all accounts where the owner is a specific name. Then update the account owner with the sales rep associated. Here is the code I currently have:

List<Account> acc = new List<Account>();
acc = [Select Id, Sales_Rep_Name__c From Account Where Owner.name = 'Bishop Lafer'];
List<User> usr = new List<User>();
for(Account ac:acc){
   usr = [Select Id From User Where Name =: ac.Sales_Rep_Name__c];
   ac.OwnerName = usr.get(0).Id; 

I am getting this error:

System.LimitException: Too many SOQL queries: 101

I tried to do the following:

for(Account ac:acc){
    ac.OwnerName = ac.Sales_Rep_Name__c;     

However you can only update the Account Owner using the Owner.Id

How can I accomplish this seemingly simple task?

Any insight is greatly appreciated, thank you for your time!

| improve this question | | | | |

You need to set the OwnerId value. Note that you can't set a null value, so unless Sales_Rep_Name__c is required, you should add a null check. If you need to query the users by name, its' a four step process.

Step 1: Query Accounts to Update

List<Account> records = [
    SELECT Sales_Rep_Name__c FROM Account
    WHERE Owner.Name = 'Somebody'
    AND Sales_Rep_Name__c != null

Step 2: Query/Map Users

Set<String> names = new Set<String>();
for (Account record : records)

Map<String, User> users = new Map<String, User>();
for (User user : [SELECT Name FROM User WHERE Name IN :names])
    users.put(user.Name, user);

Step 3: Set OwnerId

for (Account record : records)
    User rep = users.get(record.Sales_Rep_Name__c);
    if (rep != null)
        record.OwnerId = rep.Id;

Step 4: Commit the Update

update records;
| improve this answer | | | | |
  • I ran the code you suggested and I received this error: System.StringException: Invalid id: (Sales Rep Name) The Sales_Rep_Name__c is a full name not an Id, I need the Id of the user whose name = Sales_Rep_Name__c – Pohsible Aug 16 '16 at 23:38
  • See the updated snippet. @Pohsible – Adrian Larson Aug 16 '16 at 23:53
  • Thanks, I ran the updated snippet but no changes took effect. Do I need to update the Account object? – Pohsible Aug 16 '16 at 23:56
  • Yeah, I thought that part was obvious so I didn't include it in any of the snippets. Updated. – Adrian Larson Aug 16 '16 at 23:57
  • The code executed however there are still acounts Who Have Sales Reps associated with the same Owner that we used to select the accounts in the first query. @AdrianLarson – Pohsible Aug 17 '16 at 0:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.