You need to sign in to do that
Don't have an account?
Apar Jaggi 6
only variable references are allowed in dynamic soql/sosl. I am not able to understand the problem
queryStr='age__c=29'
Database.query('SELECT Id,Name,Age__c,Email__c,Course__c FROM Student__c WHERE '+queryStr+' LIMIT:20');
Database.query('SELECT Id,Name,Age__c,Email__c,Course__c FROM Student__c WHERE '+queryStr+' LIMIT:20');
The problem is with setting limit with ":" (colon). The correct way is use LIMIT 20
I tried this code and it works for me
String queryStr='NumberOfEmployees>29';
Database.query('SELECT Id,Name FROM Account WHERE '+queryStr+' LIMIT 20');
Best Regards
Gulshan Raj
In dynamic SOQL, you can only use variable references to bind values to the query, but not to dynamically build the query itself.
To fix this, you can use parameterized queries to dynamically bind the variable value to the query.
If it helps please mark this as Best Answer.
Thank you.
Furthermore, the error message “only variable references are allowed in dynamic soql/sosl” suggests that the query string passed to Database.query() must be a string literal, which means that any dynamic parts of the query (such as variable values) must be properly substituted using placeholders.
To fix this issue, you can use a parameterized query instead of concatenating the variable directly into the query string. Here’s an example:
10:49
String queryStr = ‘age__c=:ageValue’;
Map<String, Object> queryParams = new Map<String, Object>{
‘ageValue’ => 29
};
List<Student__c> students = Database.query(‘SELECT Id, Name, Age__c, Email__c, Course__c FROM Student__c WHERE ’ + queryStr + ' LIMIT 20', queryParams);
New
10:50
In this example, we define a placeholder :ageValue in the query string and pass a map of parameter values to Database.query(). This way, we can ensure that the query is properly sanitized and that the variable value is substituted safely.
If you find this answer helpful, Please mark it as the best answer.