0

I am having an issue with the database.Query. I keep getting a I think error on of my object variable doesn't exist or my where clause is incorrect. This is what I tried

 String strObjectName = soOrder.Record_Name__c; 
 String strName = soOrder.Record_id__c; 



 1.) 

  List<sObject> lstOrder = Database.query('SELECT Id FROM strObjectName WHERE Name = :strName');

2.) 

 string strQuery = 'Select Id  From ' + strObjectName + ' where Name =:  ' + strName;


List<sObject> lstOrder = Database.query(strQuery);

I am getting an error on the where clause in which when the database.Query fires it wants single quotes around it.

  • 1
    What are the errors? Could you include them in the question please? – Sander de Jong May 16 at 12:17
  • Added the error. It wants single quotes around my where clause. – CodeMonger May 16 at 12:22
4

Object name does not support bind operator; so you would need to do a concatenation for 1st scenario:

List<sObject> lstOrder = Database.query('SELECT Id FROM ' + strObjectName + ' WHERE Name = :strName');

And in your second approach, you do not need a bind operator as you're performing a String concatenation (Use escapeSingleQuotes to prevent SOQL injection):

String strQuery = 'SELECT Id  FROM ' + 
    strObjectName + 
    ' WHERE Name = ' + 
    String.escapeSingleQuotes(strName);
  • Did you try this query ? AFAIK, binding object name in dynamic SOQL query gives unexpected token exception. – Vijay Ganji May 16 at 12:31
  • @VijayGanji This is quite common scenario with dynamic SOQL, bind operator simply resolves the variable with its corresponding value. – Raul May 16 at 12:33
  • I did a quick test in anonymous window and its giving me a unexpected token exception – Vijay Ganji May 16 at 12:35
  • @VijayGanji Ah you're right!, was not quite sure hence also had added second approach :) – Raul May 16 at 12:38
2

There are different ways of doing this and it depends on the requirement.

When you are comparing a field's value with the variable, you will have to use the bind expression i.e. :, and when using bind expression, mention the variable in the query itself.

If you don't want to use the variable in SOQL, then you will have to prepare your SOQL using string concatenation, but using this approach, you will have to handle the SOQL injection as well.

Also, you cannot bind object name using bind expression, you can find further help about Dynamic SOQL at this link

Hence the simplest approach I can think of is using below query

string strQuery = 'Select Id  From ' + strObjectName + ' where Name =:strName';
List<sObject> lstOrder = Database.query(strQuery);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.