1

Here I'm trying to perform LIKE operation in SOQL when I'm passing a variable dynamically the Query is not returning the results?

List<string> companies=new list<string>();
List<Account> leadAccountIds=[Select Id, OwnerId, Name FROM Account WHERE Name LIKE : '%' + companies + '%'];

I tried Like below ways

LIKE  '%+ companies +%'
LIKE: '%companies %'
LIKE:('%'+companies+'%')

Please help me?

Thanks In Advance!...

1
  • companies is List<string>. Does it contain only one string or multiple strings?
    – sfdc_sk
    Jul 12, 2018 at 10:04

3 Answers 3

3

If you have multiple entries, you need to prepare a String like this way

Select Id, OwnerId, Name FROM Account 
WHERE Name LIKE '%ABC%' 
OR Name LIKE '%BCA%' 
OR Name LIKE '%XYZ%'

For each individual item in the list, it should be followed by LIKE operator as above.

Recommended approach as follows:

List<string> companies=new list<string>(); 
List<String> soqlLikeStr = new List<String>();

//loop through each item in companies list
for(String str:companies)
{
    soqlLikeStr.add('%'+str+'%');
}

List<Account> leadAccountIds=[Select Id, OwnerId, Name FROM Account WHERE Name LIKE :soqlLikeStr];
System.debug('leadAccountIds=' + leadAccountIds);
2
  • Hi Santanu Boral, It's true, but how to pass dynamically(Variable)
    – VINOD
    Jul 12, 2018 at 10:00
  • check my updated answer Jul 12, 2018 at 10:27
1

In List companies=new list() what it will hold List of String OR only One String?
if it holds only one String then Please replace the List with String Like below: -

String companies;
String likeFilter = '\'%'+companies+'%\'';
List<Account> leadAccountIds = new List<Account>();
String Query = 'Select Id, OwnerId, Name FROM Account WHERE Name LIKE ' + likeFilter;
leadAccountIds = Database.Query(Query);

For List of Records, You need to do Some manipulations on the List and then use Include Operator

0

You can do something Like

string tempInput = '%' + companies + '%';
[Select Id, OwnerId, Name FROM Account WHERE Name LIKE : tempInput ];

or if you are making dynamic SOQL

String val='\'%' + String.escapeSingleQuotes(inVal.trim()) + '%\'';

and then use this in the query:

' LIKE ' + val;
2
  • Hi Tushar Sharma, I tried the above way, it's not worked(not getting results). When I'm tring query in developer console its working, Why not here?
    – VINOD
    Jul 12, 2018 at 10:02
  • @VINOD if it is working in developer console that means the query is correct. Can you confirm if you have data which match filter criteria and user have proper permission? Jul 12, 2018 at 10:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .