1

I would like to select all rows from [Column] that have within their string the words in a list as so:

select [Column]
from [db]
where [Column] like '%some%' or 
      [Column] like '%word%' or
      [Column] like '%and%' or
      [Column] like '%another%' 

However, as I have a long list of words, I do not want to repeat the or [Column] like '%%'. Is there a better way to write this? I am using SQL Server Management Studio.

callmeGuy
  • 944
  • 2
  • 11
  • 28

3 Answers3

3

Use a temporary or variable table and move the WHERE to the JOIN.

DECLARE @PartialMatches TABLE (PartialMatch VARCHAR(100))

INSERT INTO @PartialMatches (PartialMatch)
VALUES ('some'),('word'),('and'),('another')

select 
    D.[Column]
from 
    [db] AS D 
    INNER JOIN @PartialMatches AS P ON D.[Column] LIKE '%' + P.PartialMatch + '%'

You can opt to include the like special characters (%) on the table or outside. Having them on the table gives more flexibility, you can put some% and %word, for example.

EzLo
  • 13,780
  • 10
  • 33
  • 38
0

This one (match list or not match list) works for me...

declare @matchs table ( match varchar(50));
declare @notmatchs table ( notmatch varchar(50));
insert into @matchs (match) values ('%matchfield1%');
insert into @notmatchs (notmatch) values ('%nomatch1'), ('nomatch2%');

select e.* 
from mytable e
where not exists (select top 1 1 from @notmatchs nm where e.ObjectName like nm.notmatch)
and exists (select top 1 1 from @matchs m where e.ObjectName like m.match)
SazooCat
  • 150
  • 1
  • 6
-1

You can write your query in below format.

select [Column]
from [db]
where [Column] like '%[some-word-and-another]%'
A.M. Patel
  • 334
  • 2
  • 9