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
Eric Blaxton 11Eric Blaxton 11 

How do I assign a List (SOQL) value to a variable

Hi and thanks in advance,

I have 2 goals here:
  • get a List Value and assign to a variable.
  • If record not found, do nothing, go to the next record. (This works)
Note: I can access the variable through acc.id if query without a list, but I get an error when a record is not found and it won't go to the next record. For example,
Account acc = [SELECT id, OwnerId, Name, AccountNumber FROM Account where AccountNumber =:ReferenceId];

Load list through query: (does not throw exception if record not found)
List<Account> acc = [SELECT id, OwnerId, Name, AccountNumber FROM Account where AccountNumber =:ReferenceId];
Access id value code (Does not work)
newcase.AccountId = acc.id;
Error:
Variable does not exist: id
Regards,
Eric


 
Best Answer chosen by Eric Blaxton 11
Eric Blaxton 11Eric Blaxton 11
In case anyone needs this.
 
newcase.AccountId = acc[0].id;

 

All Answers

Eric Blaxton 11Eric Blaxton 11
In case anyone needs this.
 
newcase.AccountId = acc[0].id;

 
This was selected as the best answer
ANUTEJANUTEJ (Salesforce Developers) 
Hi Eric,

You can try the get(0); as mentioned in the documentation [https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_list.htm] after the soql ending to get only the first record, in case if you want to traverse through the lies of records that are returned from the soql then you will have to use a for each loop, you can check this link:

>> https://www.sfdc99.com/2013/10/06/loops-for-and-foreach-loops/

Also, can you mention the context of newcase.AccountId = acc.id; as in are you creating a new record of case and assigning account id by traversing or are you looking for a specific scenario, you can mention to check further.

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.