Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LIKE operator with a variable number of search conditions, in T-SQL

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?

like image 905
Antelion Avatar asked Dec 12 '25 10:12

Antelion


1 Answers

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.

like image 75
Kevin Cook Avatar answered Dec 14 '25 01:12

Kevin Cook



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!