4

This may seem silly but I am working on an old system where we don't have separate table for project. We have a table something like this.

|        PROJECTNAME | EMPID |
|--------------------|-------|
|     casio calc new |     1 |
|           calc new |     2 |
|               tech |     3 |
| financial calc new |     4 |
|              casio |     5 |

Now what we want is to select EmpID from the above table where ProjectName can be either casio or calc. And we have user inputs for multiple selection like casio, calc. Meaning if user inputs casio, calc it should find ProjectName LIKE '%casio%' OR '%calc%'.

I really don't have any idea how can this be possible.

SELECT * FROM ProjectDetails
WHERE ProjectName LIKE 'casio, calc';

I searched for SQL LIKE with IN but I couldn't find any solution. Do anyone have idea how can I achieve this? Or any other approach to use? I am trying this on this fiddle.

Community
  • 1
  • 1
user3829465
  • 43
  • 1
  • 3
  • possible duplicate of [Using SQL LIKE and IN together](http://stackoverflow.com/questions/2318126/using-sql-like-and-in-together) – Tienou Jul 11 '14 at 13:34

4 Answers4

1

The solution is to use several LIKE conditions:

SELECT *
FROM ProjectDetails
WHERE ProjectName LIKE '%casio%'
OR ProjectName LIKE '%calc%';
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

Like doesn't except comma delimited values. You are going to have to dynamically add an or condition for each passed in value.

It has to be of the form:

ProjectName Like'%param1%' OR ProjectName Like '%param2%'
Vulcronos
  • 3,428
  • 3
  • 16
  • 24
1

Here you go. You can create a dynamic query with the help of REPLACE function with a little bit hack. Then use EXEC function to execute that query.

DECLARE @str VARCHAR(MAX)
SELECT @str='casio,calc'

SELECT @str='LIKE ''%'+REPLACE(@str,',','%'' OR ProjectName LIKE ''%')+'%'''

EXEC('SELECT * FROM ProjectDetails WHERE
     ProjectName ' + @str +'');

Output:

|        PROJECTNAME | EMPID |
|--------------------|-------|
|     casio calc new |     1 |
|           calc new |     2 |
| financial calc new |     4 |
|              casio |     5 |

SQL Fiddle Demo

Thanks to Joe G Joseph for his hint.

Community
  • 1
  • 1
Himanshu
  • 31,810
  • 31
  • 111
  • 133
0

We declare @str variable and store value we want to search and using REPLACE function place like keyword for every value and assign it to main query and execute it, you can get result

DECLARE @Query VARCHAR(MAX)
DECLARE @str VARCHAR(MAX)
SELECT @str='tech,casio, calc,casio calc new'
SELECT @str='LIKE ''%'+REPLACE(@str,',','%'' OR ProjectName LIKE ''%')+'%'''
set @Query ='SELECT * FROM ProjectDetails WHERE
     ProjectName  ' + @str
exec( @Query)