开发者

Dynamic Like Statement in SQL

开发者 https://www.devze.com 2023-02-02 23:49 出处:网络
I\'ve been racking my brain on how to do this for a while, and i know that some genius on this site will have the answer. Basically i\'m trying to do this:

I've been racking my brain on how to do this for a while, and i know that some genius on this site will have the answer. Basically i'm trying to do this:

SELECT column 
  FROM table 
 WHERE [table].[column] LIKE string1 
       OR [table].[column] LIKE string2 
       OR [table].[column] LIKE string3...

for a list of search strings stored in a column of a table. Obviously I can't do a like statement for each string by hand because i want the table to be dynamic.

Any suggestions would be great. :D

EDIT:

I'm using MSSQL 开发者_运维百科:(


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  Name
1   Fred
2   Joe
3   Frederick
4   Joseph
5   Kenneth

To find all the Freds and Jos you code

SELECT 
    *
FROM
    Table_1
WHERE 
    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  Search
1   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  Search
1   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');
0

精彩评论

暂无评论...
验证码 换一张
取 消