我已经看到 NopCommerce(C# MVC 开源电子商务)在“产品”和“变体”上使用全文搜索做了什么,并且只返回“产品”。这与您的情况非常相似,因为您想搜索“线程”和“回复”,但显然您只想返回“线程”。我已将其更改为使用线程并为您回复:
首先,创建一个按表生成索引名称的函数(可选):
CREATE FUNCTION [dbo].[nop_getprimarykey_indexname]
(
@table_name nvarchar(1000) = null
)
RETURNS nvarchar(1000)
AS
BEGIN
DECLARE @index_name nvarchar(1000)
SELECT @index_name = i.name
FROM sys.tables AS tbl
INNER JOIN sys.indexes AS i ON (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tbl.object_id)
WHERE (i.is_unique=1 and i.is_disabled=0) and (tbl.name=@table_name)
RETURN @index_name
END
GO
然后,通过创建目录和索引来启用全文:
EXEC('
IF NOT EXISTS (SELECT 1 FROM sys.fulltext_catalogs WHERE [name] = ''myFullTextCatalog'')
CREATE FULLTEXT CATALOG [myFullTextCatalog] AS DEFAULT')
DECLARE @create_index_text nvarchar(4000)
SET @create_index_text = '
IF NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(''[Table_Thread]''))
CREATE FULLTEXT INDEX ON [Table_Thread]([Subject])
KEY INDEX [' + dbo.[nop_getprimarykey_indexname] ('Table_Thread') + '] ON [myFullTextCatalog] WITH CHANGE_TRACKING AUTO'
EXEC(@create_index_text)
SET @create_index_text = '
IF NOT EXISTS (SELECT 1 FROM sys.fulltext_indexes WHERE object_id = object_id(''[Table_Replies]''))
CREATE FULLTEXT INDEX ON [Table_Replies]([ReplyText])
KEY INDEX [' + dbo.[nop_getprimarykey_indexname] ('Table_Replies') + '] ON [myFullTextCatalog] WITH CHANGE_TRACKING AUTO'
EXEC(@create_index_text)
然后,在通过关键字获取产品的存储过程中,构建一个临时表,其中包含与关键字匹配的产品 Id 列表。
INSERT INTO #KeywordThreads ([ThreadId])
SELECT t.Id
FROM Table_Thread t with (NOLOCK)
WHERE CONTAINS(t.[Subject], @Keywords)
UNION
SELECT r.ThreadId
FROM Table_Replies r with (NOLOCK)
WHERE CONTAINS(pv.[ReplyText], @Keywords)
现在您可以使用临时表#KeywordThreads
加入线程列表并返回它们。
我希望这有帮助。