In my apex code i have a variable resultField
and a List<Id> objIds
. What i need is a List<My_Obj__c> objs = [select Id, :resultField from My_Obj__c where Id in :objIds];
. This is not working because apparantly i can't specify :resultField
even though :objIds
work in the query. Is there a way to do it other than string concatinations.
-
@RahulSharma i am trying to select a second field dynamically from variable resultField. That's why there is that ,– Gurbakhshish SinghFeb 28, 2018 at 19:52
2 Answers
You cannot use Apex bindings in the SELECT
or FROM
clauses of a SOQL query. Bindings are available in the WHERE
clause.
You'll need to use Dynamic SOQL to construct your query as a string concatenation, as you mention - there's not another way to build a query with dynamic values in the SELECT
clause.
-
will it let me do
Database.query('select Id, ' + resultField + ' from My_Obj__c where Id in :objIds')
. Will it let me bind:objIds
Feb 28, 2018 at 19:50 -
Salesforce only takes bind variable in WHERE clause and not in the SELECT statement.
So, you need to perform String concatenation.