function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Krishnan MishraKrishnan Mishra 

Why i am getting the following error :System.QueryException: unexpected token: lastname

String objName = 'Contact';
string alphaSearchConct = 'A';
String fieldNames = 'name,id';
list<sObject> ct = Database.query('SELECT '+ fieldNames +'FROM '+ objName +'WHERE lastname Like:'+alphaSearchConct +'%');

 
Best Answer chosen by Krishnan Mishra
<Saket><Saket>
Hi Krishnan 

Try this
 
String objName = 'Contact';
string alphaSearchConct = 'A%';
String fieldNames = 'name,id ';
list<sObject> ct = Database.query('SELECT '+ fieldNames +'FROM '+ objName +' WHERE lastname Like :alphaSearchConct');

 

All Answers

Raj VakatiRaj Vakati
Here is the code
 
String objName = 'Contact';
string alphaSearchConct = 'A';
String fieldNames = 'name,id';
String query = 'SELECT '+ fieldNames +' FROM '+ objName +' WHERE lastname like \'%'+alphaSearchConct +'%\'' ; 
System.debug('query'+query);
list<sObject> ct = Database.query(query);

 
<Saket><Saket>
Hi Krishnan 

Try this
 
String objName = 'Contact';
string alphaSearchConct = 'A%';
String fieldNames = 'name,id ';
list<sObject> ct = Database.query('SELECT '+ fieldNames +'FROM '+ objName +' WHERE lastname Like :alphaSearchConct');

 
This was selected as the best answer
Krishnan MishraKrishnan Mishra
Hi Saket,
That too is not working it is now showing 
System.QueryException: unexpected token: WHERE
<Saket><Saket>
Hi Krishnan its working in mine org I tested it , Please copy the entire code which I provided u and paste it in anonymous window and run I think it will work .
Raj VakatiRaj Vakati
Use this code
 
String objName = 'Contact';
string alphaSearchConct = 'A';
String fieldNames = 'name,id';
String query = 'SELECT '+ fieldNames +' FROM '+ objName +' WHERE lastname like \'%'+alphaSearchConct +'%\'' ; 
System.debug('query'+query);
list<sObject> ct = Database.query(query);