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
Swamy PSwamy P 

System.QueryException: expecting a colon, found 'VIJ'

Hello Folks,

In Apex Class i'm using dynamic SOQL, below is my code:
 string soql='select id,name,Area__c,City__c,Address__c from User_Detail__c where name!=null';
        if(usr.Area__c!=null){
            soql+=' and Area__c=:\''+usr.Area__c+'\'';
        }
System.Debug('Query '+soql);
        List<User_Detail__c> userDetailRecords=Database.query(soql);

Debug is: 
DEBUG|Query select id,name,Area__c,City__c,Address__c from User_Detail__c where name!=null and City__c=VIJ

Error Message: 
System.QueryException: expecting a colon, found 'VIJ'

I thought everything i have given correctly, but missed something somwhere. Will you correct me where i'm supposed to change.
Please update me your thoughts ASAP
RohRoh

Hello Swamy,
Try modifying it as below ,

string soql='select id,name,Area__c,City__c,Address__c from User_Detail__c where name!=null';
        if(usr.Area__c!=null){
            soql+=' and Area__c=\''+usr.Area__c+'\' LIMIT 1';
        }
System.Debug('Query '+soql);
        List<User_Detail__c> userDetailRecords=Database.query(soql);

PLEASE SELECT THIS AS THE BEST ANSWER, IF YOU LIKE IT.

Thanks,
Rohit Alladi
Swamy PSwamy P
Hello Roh,

No its not working and again same error coming. Compare to my code i think you have added "Limit condition" but no luck. Will you check it once again, plz?
RohRoh
Hey Swamy,
I changed the colon and added the limit earlier.
I ran the same in my execute anonymous and checked below,

String VJW = 'VJW' ;
String soql = 'Select id,Name from object__c where name!=null and name = ' + '\'' + VJW + '\'';
system.debug('SOQL --' + soql);
database.query(soql);
08:50:20.23 (23867330)|USER_DEBUG|[3]|DEBUG|SOQL --Select id,Name from object__c where name!=null and name = 'VJW'

Check if there are any escape characters in the field ?
else try hardcoding the value first to VJW and check .

Let me know

Thanks,
Rohit Alladi
Temoc MunozTemoc Munoz
That's correct Roh.

For future references, please refer to this Swamy

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dynamic_soql.htm