Only variable references are allowed in dynamic SOQL/SOSL

I’m trying to re-request an Asset from the database:

asset = Database.query('SELECT ID, Price, Asset_MRR__c FROM Asset WHERE id =: ' + asset.id + ' limit 1');

But I get an error:

Only variable references are allowed in dynamic SOQL/SOSL

What am I doing wrong?

Answer

If you use : in your query, Apex expects a variable. In case you are querying with the string, you should not use the :, but escape single quotes(\'). So your query should look like this:

asset = Database.query('SELECT ID, Price, Asset_MRR__c FROM Asset WHERE id =\'' + asset.id + '\' limit 1');

You could also use :, but then just put asset.id in your query string:

asset = Database.query('SELECT ID, Price, Asset_MRR__c FROM Asset WHERE id =:asset.id limit 1');

EDIT

Just checked the second example in developer console with this code:

String testName = 'test';
List<Account> accList = Database.query('SELECT Id, Name FROM Account WHERE Name = :testName');
System.debug('accList: ' + accList);

The output was:

09:09:32:100 USER_DEBUG [3]|DEBUG|accList: (Account:{Id=0018E000005L8D3QAK, Name=test, RecordTypeId=012w0000000QSfUAAW}, Account:{Id=0018E000007eRInQAM, Name=test, RecordTypeId=012w0000000QMrxAAG})

Also, using LIMIT 1 when querying with WHERE Id = ... is not necessary, ids are unique anyway, so you will get 0 or 1 results anyway.

Attribution
Source : Link , Question Author : Sergey , Answer Author : Novarg

Leave a Comment