Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - A join using full-text CONTAINS

I currently have the following select statement, but I wish to move to full text search on the Keywords column. How would I re-write this to use CONTAINS?

SELECT MediaID, 50 AS Weighting
FROM Media m JOIN @words w ON m.Keywords LIKE '%' + w.Word + '%'

@words is a table variable filled with words I wish to look for:

DECLARE @words TABLE(Word NVARCHAR(512) NOT NULL);
like image 510
Sprintstar Avatar asked Mar 17 '26 18:03

Sprintstar


2 Answers

If you are not against using a temp table, and EXEC (and I realize that is a big if), you could do the following:

DECLARE @KeywordList VARCHAR(MAX), @KeywordQuery VARCHAR(MAX)
SELECT @KeywordList = STUFF ((
        SELECT '"' + Keyword + '" OR '
        FROM FTS_Keywords
        FOR XML PATH('')
    ), 1, 0, '')

SELECT  @KeywordList = SUBSTRING(@KeywordList, 0, LEN(@KeywordList) - 2)
SELECT  @KeywordQuery = 'SELECT RecordID, Document FROM FTS_Demo_2 WHERE CONTAINS(Document, ''' + @KeywordList +''')'

--SELECT @KeywordList, @KeywordQuery

CREATE TABLE #Results (RecordID INT, Document NVARCHAR(MAX))

INSERT INTO #Results (RecordID, Document)
EXEC(@KeywordQuery)

SELECT * FROM #Results

DROP TABLE #Results

This would generate a query like:

SELECT   RecordID
        ,Document 
FROM    FTS_Demo_2 
WHERE CONTAINS(Document, '"red" OR "green" OR "blue"')

And results like this:

RecordID    Document
1   one two blue
2   three red five
like image 85
Tom Halladay Avatar answered Mar 20 '26 09:03

Tom Halladay


If CONTAINS allows a variable or column, you could have used something like this.

SELECT MediaID, 50 AS Weighting
FROM Media m
JOIN @words w ON CONTAINS(m.Keywords, w.word)

However, according to Books Online for SQL Server CONTAINS, it is not supported. Therefore, no there is no way to do it.

Ref: (column_name appears only in the first param to CONTAINS)

CONTAINS
( { column_name | ( column_list ) | * } 
  ,'<contains_search_condition>'     
[ , LANGUAGE language_term ]
) 
like image 22
RichardTheKiwi Avatar answered Mar 20 '26 07:03

RichardTheKiwi



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!