我目前有以下select语句,但我希望转到关键字列的全文搜索。我将如何重写这个以使用CONTAINS?
SELECT MediaID, 50 AS Weighting
FROM Media m JOIN @words w ON m.Keywords LIKE '%' + w.Word + '%'
@words是一个表变量,里面填充了我想要查找的单词:
DECLARE @words TABLE(Word NVARCHAR(512) NOT NULL);
答案 0 :(得分:4)
如果您不反对使用临时表和EXEC(我意识到这是一个很大的问题),您可以执行以下操作:
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
这将生成如下查询:
SELECT RecordID
,Document
FROM FTS_Demo_2
WHERE CONTAINS(Document, '"red" OR "green" OR "blue"')
结果如下:
RecordID Document
1 one two blue
2 three red five
答案 1 :(得分:2)
如果CONTAINS允许变量或列,则 可能 使用此类内容。
SELECT MediaID, 50 AS Weighting
FROM Media m
JOIN @words w ON CONTAINS(m.Keywords, w.word)
但是,根据SQL Online的联机丛书CONTAINS,它不受支持。因此,没有办法做到这一点。
参考:( column_name仅出现在CONTAINS的第一个参数中)
CONTAINS
( { column_name | ( column_list ) | * }
,'<contains_search_condition>'
[ , LANGUAGE language_term ]
)