+ Start a Discussion
Priyadarshi NayakPriyadarshi Nayak 

Dynamic SOQL - System.QueryException: expecting a colon

The following mentioned in APEX Guide does not work!


You can instead resolve the variable field into a string and use the string in your dynamic SOQL query:

String resolvedField1 = myVariable.field1__c;
List<sObject> sobjList = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c
= ' + resolvedField1);

I have used following code but encountered error "System.QueryException: expecting a colon, found 'Xmerged3'"
String name3 ='Xmerged3';
Account myA3 = Database.query('SELECT ID, NAME from account where name='+name3); 
//System.QueryException: expecting a colon, found 'Xmerged3'
System.debug('Account2'+myA3.name); 
Any pointer why its failing?
Malni Chandrasekaran 2Malni Chandrasekaran 2
Priyadarshi Nayak,
Please try putting colon : before variable 'name3' in your query as given below

Account myA3 = Database.query('SELECT ID, NAME from account where name= :'+ name3); 
RKSalesforceRKSalesforce
Please change your query to :
Account myA3 = Database.query('SELECT ID, NAME from account where name= :'+ name3);
Basiacally, It is known as variable binding.
We can write your query in following way as well:
Account myA3 = [SELECT ID, NAME from account where name =: name3];

Plese mark it as best answer if it helped.

Regards,
Ramakant
 
 
Karan Shekhar KaulKaran Shekhar Kaul

Hi,
 

Try 

String name3 ='Xmerged3';
Account myA3 = Database.query('SELECT ID, NAME from account where name=:name3');
//System.QueryException: expecting a colon, found 'Xmerged3'
System.debug('Account2'+myA3.name);&nbsp;