About this question
Whenever I request an asset from the data table, I encounter the following error that shows that only variable references are acceptable in dynamic SOQL or SOSL. Please help me understand if there is anything wrong I am doing.
Whenever I request an asset from the data table, I encounter the following error that shows that only variable references are acceptable in dynamic SOQL or SOSL. Please help me understand if there is anything wrong I am doing.
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask Salesforce Expert
Answered on Aug 30, 2023
If you get only variable references allowed in dynamic SOQL/SOSL, you must understand that Apex usually needs a variable if you use: in the queue you provide. But if you use a string, you need to escape single quotes (’), which makes the query look like the following one:
asset = Database.query('SELECT ID, Price, Asset_MRR__c FROM Asset WHERE id ='' + asset.id + '' limit 1');
Since the dynamic SOQL documentation describes that simple bind variables can be used, there should be a reference to every variable. So, follow the below-mentioned pattern, which can assign a more complicated expression to a variable in a dynamic SOQL:
Id assetId = asset.Id;
asset = Database.query('SELECT ID, Price, Asset_MRR__c FROM Asset WHERE id =:assetId limit 1');Also, you can try any of the following two codes:

'Select ' + fieldName + ' FROM ' + objectName + ' WHERE Id = '' + com.Account_Lookup__c + '''+' Limit 1'
Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Step-by-step Salesforce guides from industry experts
Common Salesforce interview questions, answered
Guides, tips and career advice on Salesforce from JanBask experts.
Salesforce How to Become a Salesforce Developer Without Experience
No coding background? Learn how to become a Salesforce Developer step by step - skills to build, projects to create, and how to…
Salesforce How to Become a Salesforce Admin With No Experience
No Salesforce Admin experience? Learn how to build real skills, create projects, and land an entry-level Salesforce Admin job…
Salesforce How Long Does It Take to Become a Salesforce Developer?
Wondering how long to learn Salesforce Developer? Most beginners need 6–12 months. See the study time, stage-by-stage roadmap and…
Salesforce How Long Does It Take to Become a Salesforce Admin?
Wondering how long to learn Salesforce Admin? Most beginners need 3–6 months. See the study time, stage-by-stage roadmap and…