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
SirTravSirTrav 

database.query using like and % giving error

I am trying to do a soql query using database.query so that I can dynamically build the search parameters.  the problem I am having is with the following portion:
qry3 = qry2 + 'where name like :%' + sobj.name + '% OR Account__c = :' + sobj.Account__c + ' OR Opportunity__c = :' + sobj.Opportunity__c + ' limit 50';
when I put it in this way I get the error : no viable alternative at character '%'
I have tried:
qry3 = qry2 + 'where name like :\'%' + sobj.name + '%\' OR Account__c = :' + sobj.Account__c + ' OR Opportunity__c = :' + sobj.Opportunity__c + ' limit 50';
when I do it this way I get the error: unexpected token: '%test test%'
and I have tried it this way: 
qry3 = qry2 + 'where name like :\'%\'' + sobj.name + '\'%\' OR Account__c = :' + sobj.Account__c + ' OR Opportunity__c = :' + sobj.Opportunity__c + ' limit 50';
and I get the error: unexpected token: '%'

Any idea what I need to change to get the like statement to work?
Best Answer chosen by SirTrav
srinu_SFDCsrinu_SFDC
I was in haste earlier, Please try this(Only difference from your 2nd version is removed the colon)
String qry3 = qry2 + 'where name like \'%' + sobj.name + '%\' OR Account__c = :' + sobj.Account__c + ' OR Opportunity__c = :' + sobj.Opportunity__c + ' limit 50';

All Answers

srinu_SFDCsrinu_SFDC
Try this: String name = '%'+ sobj.name + '%';
qry3 = qry2 + 'where name like :' + name + ' OR Account__c = :' + sobj.Account__c + ' OR Opportunity__c = :' + sobj.Opportunity__c + ' limit 50';
srinu_SFDCsrinu_SFDC
I was in haste earlier, Please try this(Only difference from your 2nd version is removed the colon)
String qry3 = qry2 + 'where name like \'%' + sobj.name + '%\' OR Account__c = :' + sobj.Account__c + ' OR Opportunity__c = :' + sobj.Opportunity__c + ' limit 50';
This was selected as the best answer
SirTravSirTrav
Thank you that did the trick.