What is the issue if I get only variable references that are allowed in dynamic SOQL/SOSL?

513    Asked by bruce_8968 in Salesforce , Asked on Aug 30, 2023

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 SOSLPlease help me understand if there is anything wrong I am doing. 

 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'

Your Answer

Interviews

Parent Categories