Dynamic Like Statement in SQL
Put the parameters (string1, string2, string3...) into a table (Params
) then JOIN
to the table using LIKE
the JOIN
clause e.g.
SELECT column FROM table AS T1 INNER JOIN Params AS P1 ON T1.column LIKE '%' + P1.param + '%';
Make a sample Table_1:
id Name1 Fred2 Joe3 Frederick4 Joseph5 Kenneth
To find all the Freds and Jos you code
SELECT *FROM Table_1WHERE name like 'Fred%' OR name like 'Jo%'
What you'd like is a dynamic WHERE. You can achieve this by putting the wildcards in Table_2:
id Search1 Fred%2 Jo%
and performing the LIKE with an INNER JOIN:
SELECT *FROM Table_1 INNER JOIN Table_2 ON Table_1.name LIKE Table_2.search
Result:
id Name id Search1 Fred 1 Fred%3 Frederick 1 Fred%2 Joe 2 Jo%4 Joseph 2 Jo%
Sounds like you are trying to do a fulltext search. MySQL has a tool for this:
http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html
SELECT column FROM table MATCH (column) AGAINST ('string1 string2 string3' IN BOOLEAN MODE)
In case of MSSQL some information is available at
http://msdn.microsoft.com/en-us/library/cc879300.aspx
SELECT column FROM table WHERE CONTAINS (column , 'string1 string2 string3');