是否有一种简短的方法可以使用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语句?
答案 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)
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)