Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combination of 'LIKE' and 'IN' using t-sql

How can I do this kind of selection:

SELECT *  FROM Street  WHERE StreetName LIKE IN ('% Main Street', 'foo %') 

Please don't tell me that I can use OR because these actually comes from a query.

like image 424
Panagiotis Lefas Avatar asked May 23 '11 20:05

Panagiotis Lefas


People also ask

Is there a combination of like AND in in SQL?

There is no combination of LIKE & IN in SQL, much less in TSQL (SQL Server) or PLSQL (Oracle).

How do you do multiple like conditions in SQL?

Using the LIKE operator, you can specify single or multiple conditions. This allows you to perform an action such as select, delete, and updating any columns or records that match the specified conditions. It is mainly paired with a where clause to set the conditions.

What does like %% mean in SQL?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Can we use multiple like in SQL?

No, MSSQL doesn't allow such queries.


2 Answers

There is no combined LIKE and IN syntax but you can use LIKE to JOIN onto your query as below.

;WITH Query(Result) As ( SELECT '% Main Street' UNION ALL SELECT 'foo %' ) SELECT DISTINCT s.*  FROM Street s JOIN Query q ON StreetName LIKE q.Result 

Or to use your example in the comments

SELECT DISTINCT s.*  FROM Street s JOIN CarStreets cs ON s.StreetName LIKE cs.name + '%' WHERE cs.Streets = 'offroad' 
like image 87
Martin Smith Avatar answered Oct 24 '22 00:10

Martin Smith


You don't have a lot of choices here.

SELECT * FROM Street Where StreetName LIKE '% Main Street' OR StreetName LIKE 'foo %' 

If this is part of an existing, more complicated query (which is the impression I'm getting), you could create a table value function that does the checking for you.

SELECT * FROM Street Where StreetName IN (dbo.FindStreetNameFunction('% Main Street|foo %')) 

I'd recommend using the simplest solution (the first). If this is nested inside a larger, more complicated query, post it and we'll take a look.

like image 31
James Hill Avatar answered Oct 23 '22 22:10

James Hill