Sql-server – How to perform a full-text CONTAINS call across a list of phrases

full-text-searchsql serversql-server-2008-r2t-sql

I have a list of words/phrases in a table phrases. I have another table with a full-text catalog indexing the description column.

I want to populate a table results with a record for each phrase, and the number of times that phrases was found in the description:

INSERT INTO results(phrase, foundcount)
SELECT  phrase, 
    (SELECT COUNT(*) FROM table WHERE CONTAINS(table.description, phrase))
FROM    phrases;

No matter how I try, this results in the error:

Incorrect syntax near `phrase`. Expecting STRING, TEX_LEX, or VARIABLE

I would really rather not use a cursor just so I can assign each phrase to a variable. Is that really the only option?

Best Answer

Try this:

go
create function dbo.fn_GetCountForPhrase (@phrase varchar(500))
    returns  int
as
begin
    declare @count int
    declare @localphrase varchar(8000)
    set @localphrase='"' + @phrase + '"'
    SELECT @count=COUNT(*) FROM table  a WHERE CONTAINS(table.description,   @localphrase)
    return @count
end
go
SELECT  
    phrase,  
    dbo.fn_GetCountForPhrase(phrase) 
FROM phrases