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
Himanshu GhateHimanshu Ghate 

I am getting problem form this code? Can some please help me.

String accountdata='Hello';
String dyncquery='Select id, Name,     Industry , Type From Account';
if(accountdata=='Hello')
{
    dyncquery +='WHERE      Industry=\'Agriculture\'  AND Type=\'Prospect\'';
}else if(accountdata=='Helloworld')
{
    dyncquery +='WHERE      Industry=\'Banking\'  AND Type=\'Customer - Direct\'  ';
}
else{
    dyncquery +='WHERE     Industry=\'Construction\'     ';
}
List<Account> accounts=Database.query(dyncquery);
System.debug('Account Record:'+accounts);
System.debug('Account Size:'+accounts.size());Even if ,Inside the account object the industry field is present it showing the error like this.When I remove the Industry ,Then it show on Type that 
Line: 13, Column: 1
System.QueryException: unexpected token: Type
Line: 13, Column: 1
System.QueryException: unexpected token: Industry
 
Best Answer chosen by Himanshu Ghate
SwethaSwetha (Salesforce Developers) 
HI Himanshu,
Try below updated code
 
String accountdata='Hello';
String dyncquery='Select id, Name,     Industry , Type From Account';
if(accountdata=='Hello')
{
    dyncquery +=' WHERE      Industry=\'Agriculture\'  AND Type=\'Prospect\'';
}else if(accountdata=='Helloworld')
{
    dyncquery +=' WHERE      Industry=\'Banking\'  AND Type=\'Customer - Direct\'  ';
}
else{
    dyncquery +=' WHERE     Industry=\'Construction\'     ';
}
List<Account> accounts=Database.query(dyncquery);
System.debug('Account Record:'+accounts);
System.debug('Account Size:'+accounts.size());
Basically, you need to give space before WHERE condition in your dynamic query 

If this information helps, please mark the answer as best. Thank you
 

All Answers

SwethaSwetha (Salesforce Developers) 
HI Himanshu,
Try below updated code
 
String accountdata='Hello';
String dyncquery='Select id, Name,     Industry , Type From Account';
if(accountdata=='Hello')
{
    dyncquery +=' WHERE      Industry=\'Agriculture\'  AND Type=\'Prospect\'';
}else if(accountdata=='Helloworld')
{
    dyncquery +=' WHERE      Industry=\'Banking\'  AND Type=\'Customer - Direct\'  ';
}
else{
    dyncquery +=' WHERE     Industry=\'Construction\'     ';
}
List<Account> accounts=Database.query(dyncquery);
System.debug('Account Record:'+accounts);
System.debug('Account Size:'+accounts.size());
Basically, you need to give space before WHERE condition in your dynamic query 

If this information helps, please mark the answer as best. Thank you
 
This was selected as the best answer
Himanshu GhateHimanshu Ghate
It worked. Thanks a lot.