function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
BMIZZYBMIZZY 

A Basic SOQL Question

I'm trying to put together an APEX class that will the User table and return the ID, based on a custom variable called Sales__c, for that user.  The ID will then be used to change the OwnerID field on the Account record.

 

Regardless of what I can think to try, I keep running in to walls.  Would greatly appreciate a gentle prodding in the correct direction.

 

 

Account[] Users = [Select a.Owner.Id, a.Owner.Sales__c from Account a  WHERE a.Owner.Sales__c  = '6579'];
           
a.OwnerID= Users.Id;

Force2b_MikeForce2b_Mike

The query itself should work. What specific issue/error are you running into?

 

Also, you can query Account.OwnerID directly to get the OwnerID instead of Account.Owner.ID. Also, could the variable name of Users be part of the issue? Maybe rename to acctOwners depending on the error you're getting. 

 

Another thing to look out for is the 1000 record limit on queries in this format. For larger result sets you should use a for loop.

 

Mike 

Caleb_SidelCaleb_Sidel

Your query:

 

Account[] Users = [Select a.Owner.Id, a.Owner.Sales__c from Account a  WHERE a.Owner.Sales__c  = '6579'];
           

Is returning a list of Accounts not Users so you have two issues.

1) You can't assign an Account Id as the owner of an Account

2) You have to specify which element in the list you want to use Users[0] or Users[1] not simply Users.id

 

If you want to get a list of Users you can query:

 

User[] userList = [Select Id From User Where Sales__c = '6579'];

 

This assumes that the User object has a custom field called Sales.

 

Then you can do something like

 

Account a;

a.OwnerId= userList [0].Id;

 

or simply

 

a.owner = userList[0];

 

If the Sales field on User is unique then you can query:

 

User u = [Select Id From User Where Sales__c = '6579' LIMIT 1];

Account a;

a.OwnerId = u.Id;

 

Hope that helps some,

Caleb