Forum Discussion
wilheim
Jun 03, 2021Copper Contributor
SQL Query Help - Searching With Multiple Search Terms
Hello, I have a need to search a column for a dynamic number of search terms. I've been doing a bit of googling and come up with this: SELECT * FROM Products as P Where Exists (select value fro...
olafhelper
Jun 04, 2021Bronze Contributor
Next time, please format your SQL code more readable, instead of one long line.
One possible solution is to coun the occurance of the search words. Example:
declare @prod as table (id int identity(1,1), descr varchar(100));
insert INTO @prod (descr)
values ('Yellow'), ('screwdriver'), ('25mm yellow screwdriver'), ('25mm screwdriver, yellow');
declare @search varchar(100) = '25mm yellow screwdriver';
with cte as
(select p.descr,
count(*) as cnt,
(select count(*) from string_split(@search, ' ')) as target
from @prod as P
cross apply
string_split('25mm yellow screwdriver', ' ') as s
where p.descr like '%' + s.value + '%'
group by p.descr)
select *
from cte
where cte.cnt = cte.target
Olaf