Is there a short way to look for multiple matches with the LIKE operator, using AND clauses?
I should do it dynamically, with a variable number of terms. Obtaining it statically (with a fixed number of terms) is a no-brainer:
SELECT *
from MyTable
WHERE MyColumn LIKE "%AAA%"
AND MyColumn LIKE "%BBB%"
AND MyColumn LIKE "%CCC%"
Let's assume there is a table variable that contains an unknown number of terms:
DECLARE @Terms table
(
Term nvarchar(500)
)
Is there a way to perform the LIKE statement on MyColumn matching all the items in @Terms?
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
This will only pull the record which matches ALL of the possible likes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With