[SalesForce] Like Operator is not working with Dynamic Variable in SOQL Query

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!…

Best Answer

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);