Possible to use bind :variable inside SELECT clause?
You have to use dynamic SOQL if you want to add fields dynamically. Merge syntax is not supported.
List<String> fields = new List<String> { 'Id', 'Name' };
String soql = 'SELECT ' + String.join(fields, ',') + ' FROM MyObject__c WHERE ...';
List<MyObject__c> records = Database.query(soql);
I actually often have dynamic filters as well when I'm in such a scenario, and might use a similar strategy there. Another basic example:
List<String> fields = new List<String> { 'Id', 'Name' };
List<String> filters = new List<String> { 'CreatedDate = TODAY', '...' };
String soql = String.format('SELECT {0} FROM MyObject__c WHERE {1}', new List<String> {
String.join(fields, ', '), String.join(filters, ' AND ')
});
List<MyObject__c> records = Database.query(soql);
You'll need to use a dynamic query for that: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm
Here's an example from the article to show a bit about how it works:
String myTestString = 'TestName';
List<sObject> sobjList = Database.query('SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString');
Basically, you'll just update it to look more like this:
String myTestString = 'TestName';
List<sObject> sobjList = Database.query('SELECT Id, ' + ss + ' FROM MyCustomObject__c WHERE Name = :myTestString');
Salesforce does not support variable binding in the SELECT
clause.
From Using Apex Variables in SOQL and SOSL Queries:
SOQL and SOSL statements in Apex can reference Apex code variables and expressions if they’re preceded by a colon (:). This use of a local code variable within a SOQL or SOSL statement is called a bind. The Apex parser first evaluates the local variable in code context before executing the SOQL or SOSL statement. Bind expressions can be used as:
- The search string in FIND clauses.
- The filter literals in WHERE clauses.
- The value of the IN or NOT IN operator in WHERE clauses, allowing filtering on a dynamic set of values. Note that this is of particular use with a list of IDs or Strings, though it works with lists of any type.
- The division names in WITH DIVISION clauses.
- The numeric value in LIMIT clauses.
- The numeric value in OFFSET clauses.
Bind expressions can't be used with other clauses, such as INCLUDES.