I have a SQL Server database that I\'m searching for keywords.
All I need to know is how many of the keywords appear in a column.
For example
Try this one
WITH C(txt) AS(
SELECT 'I like red shoes but not blue'
UNION
SELECT 'I like red shoes and green shoes, but green are my favourite'
)
SELECT COUNT(txt)
FROM C WHERE txt LIKE '%green%'
OR txt LIKE '%blue%'
OR txt LIKE '%red%'
You can use a string splitter for this. Here is the DelimitedSplit8K function by Jeff Moden.
DECLARE @str VARCHAR(8000) = 'I like red shoes and green shoes, but green are my favourite'
SELECT
COUNT(DISTINCT ITEM)
FROM dbo.DelimitedSplit8K(@str, ' ')
WHERE
Item IN('red', 'green', 'blue')
SQL Fiddle
This will work
create table #temp(color varchar(500))
insert into #temp(color) values('red')
insert into #temp(color) values('green')
insert into #temp(color) values('blue')
Create table #temp2(string varchar(max))
insert into #temp2(string) values('I like red shoes and green shoes, but green are my favourite')
insert into #temp2(string) values('I like red shoes and green shoes')
select string,count(*) from #temp inner join #temp2 on PATINDEX('%'+color+'%',string)>0
group by string
Try this
SELECT b.LineText, count(*) from
FROM
(
select 'RED' Colors
union
select 'GREEN'
union
select 'BLUE'
) a
JOIN
(
SELECT 'I like red shoes but not blue' LineText
UNION
SELECT 'I like red shoes and green shoes, but green are my favourite'
) b ON b.LineText LIKE '%'+a.Colors+'%'
group by b.LineText