0

I have a column in a table that I want to search using like. For example

SELECT * from Employee
WHERE Employee.LName like ('%Mac%', '%Smi%', '%Wal%')

When I try that, it doesn't work. I'd like to be able to do something like that, rather than like

SELECT * from Employee
WHERE Employee.LName like '%Mac%'
OR Employee.LName like '%Smi%'
OR Employee.LName like '%Wal%'
3
  • Is your list of potential matches arbitrarily long? Is it dynamic? In either your "default" solution or @Sparky's with the temp table may be faster with PATINDEX then like. Commented Mar 7, 2014 at 22:27
  • The list of matches is going to be hardcoded in (and probably added to a little bit over time). I've never heard of PATINDEX. Commented Mar 7, 2014 at 22:30
  • Definitely look up PATINDEX (and CHARINDEX for that matter). One discussion of LIKE vs PATINDEX can be found stackoverflow.com/questions/8052425. Commented Mar 8, 2014 at 0:37

3 Answers 3

2

I don't know if this is easier but it is an option
It is nice if you need to mock up a join

  SELECT [docEnum1].[value]
    FROM [docEnum1]
    join ( values ('%new%'), ('%allen%'), ('%waste%')
         ) as [joinVals] (val)
      on [docEnum1].[value] like [joinVals].[val]
Sign up to request clarification or add additional context in comments.

2 Comments

Not really that different from the below answer, right?
You mean the above accepted solution? One it does not create a #temp table? Really you think a solution with more code and #temp is simpler? What if #lookfor is in use?
1

Try this:

create table #lookfor (LikeName varchar(32))
insert into #lookfor values ('%Mac%'),('%Smi%'),('%wal%')


select * 
from employee emp 
join #lookfor lf on emp.LastName like lf.Likename
  • Build a temporary table to hold the expressions.
  • Join your main table and #temp table using the LIKE operator

1 Comment

I've been really busy at work so haven't had time to try this yet, but I really like the simplicity of this solution.
0

On SQL Server, you can do just the same w/o temp tables, but with the same simplicity, using a table variable:

DECLARE @lookfor TABLE (LikeName VARCHAR(50))
INSERT INTO @lookfor(LikeName) VALUES ('%Mac%'),('%Smi%'),('%wal%');

SELECT * 
FROM employee emp 
JOIN @lookfor lf ON emp.LastName LIKE lf.Likename

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.