在T-SQL中具有可变数量的搜索条件的LIKE运算符

时间:2014-07-01 12:45:07

标签: sql-server tsql sql-server-2008-r2 search-engine sql-like

是否有一种简短的方法可以使用AND子句来查找与LIKE运算符的多个匹配?

我应该动态地使用可变数量的术语。静态获取它(具有固定数量的术语)是明智的:

 SELECT *
 from MyTable
 WHERE MyColumn LIKE "%AAA%"
    AND MyColumn LIKE "%BBB%"
    AND MyColumn LIKE "%CCC%"

假设有一个表变量包含未知数量的术语:

DECLARE @Terms table
        (
        Term nvarchar(500)
        )

有没有办法在MyColumn上执行匹配@Terms中所有项目的LIKE语句?

4 个答案:

答案 0 :(得分:3)

DECLARE @Terms TABLE
(
    WildCards VARCHAR(20)
)

INSERT INTO @Terms
( WildCards )
VALUES
( 'CO' ),
( 'DO' ),
( 'EO' )

DECLARE @FoundAll INT
SELECT @FoundAll = Count(*) FROM @Terms

SELECT mt.MyColumn, COUNT(*), @FoundAll FROM MyTable mt
OUTER APPLY
(
    SELECT WildCards FROM @Terms
) d
WHERE mt.MyColumn LIKE ('%' + d.WildCards + '%')
GROUP BY mt.MyColumn
HAVING COUNT(*) = @FoundAll

这只会拉出与所有可能的喜欢相匹配的记录。

答案 1 :(得分:1)

SQL Fiddle

select mt.*
  from MyTable mt
  join @Terms t
    on mt.MyColumn like '%' + t.Term + '%'
 group by mt.MyColumn
having COUNT(*) = (select COUNT(*) from @Terms)

答案 2 :(得分:0)

如果您可以在不使用LIKE的情况下逃脱,那么以下方法将起作用:

SELECT * 
FROM MyTable
WHERE MyColumn IN
(
  SELECT Term 
  FROM Terms
)

或者,以下(SQL Fiddle)如何:

SELECT * 
FROM MyTable
INNER JOIN Terms 
  ON MyTable.MyColumn LIKE '%' + Terms.Term + '%'   

答案 3 :(得分:0)

试试这个:

SELECT      MT.* 
FROM        MyTable AS MT INNER JOIN
            @Terms AS TR ON CHARINDEX(TR.Term, MT.MyColumn) > 0
GROUP BY    MT.MyColumn
HAVING      COUNT(*) = (SELECT COUNT(*) FROM Terms)