我需要对SQL Server 2008 R2数据库中1到3个字段中的子字符串执行全文搜索。只能搜索具有非空搜索词的字段。我使用Entity Framework并且搜索是更大的LINQ查询的一部分,因此必须在表值函数中完成它才能组合。因此,没有动态SQL可能。到目前为止,我已经提出了以下UDF:
CREATE FUNCTION [dbo].[SearchPublications]
(
@version int,
@comment nvarchar(4000),
@description nvarchar(4000),
@tags nvarchar(4000)
)
RETURNS
@Table_Var TABLE
(
[ID] [int] NOT NULL,
[IDPublicationType] [int] NOT NULL,
[IDCover] [int] NULL,
[IDSmallCover] [int] NULL,
[IDContent] [int] NOT NULL,
[Cost] [decimal](10, 2) NOT NULL,
[Language] [smallint] NOT NULL,
[Flags] [tinyint] NOT NULL,
[Year] [smallint] NOT NULL,
[Guid] [nvarchar](255) NOT NULL,
[Key] [nvarchar](25) NOT NULL,
[CTime] [datetime] NOT NULL
)
AS
BEGIN
declare @commentParam nvarchar(4000), @descriptionParam nvarchar(4000), @tagsParam nvarchar(4000), @guid nvarchar(32) = 'E442FB8EA8624E289BD13753480AFA8B'
select @commentParam = isnull('"' + @comment + '*"', @guid)
select @descriptionParam = isnull('"' + @description + '*"', @guid)
select @tagsParam = isnull('"' + @tags + '*"', @guid)
insert @Table_Var
select *
from Publications
where (@commentParam = @guid or exists (select
1 from PublicationFields
where IDPublication = Publications.ID and IDField = 3 and IDVersion = @version and
contains(LongValue, @commentParam)
))
and (@descriptionParam = @guid or exists (select
1 from PublicationFields
where IDPublication = Publications.ID and IDField = 4 and IDVersion = @version and
contains(LongValue, @descriptionParam)
))
and (@tagsParam = @guid or exists (select
1 from PublicationFields
where IDPublication = Publications.ID and IDField = 5 and IDVersion = @version and
contains(LongValue, @tagsParam))
)
RETURN
END
但是,使用@param = @guid or...
构造从搜索中排除空参数会导致高度次优的查询计划和搜索,最多需要10秒才能完成。没有所述构造的相同搜索几乎立即返回,但在这种情况下,我不能使用可变数量的搜索项。当动态SQL不可能时,是否有更优化的方法从查询中排除WHERE子句的一部分?我希望避免为3个搜索参数的每个组合编写单独的TVF。
答案 0 :(得分:0)
回答我自己的问题:解决方案是编写一个只搜索一个指定字段的函数
CREATE FUNCTION [dbo].[SearchPublications]
(
@version int,
@field int,
@search nvarchar(4000)
)
RETURNS TABLE
AS
RETURN
(
select Publications.*
from Publications, PublicationFields
where IDPublication = Publications.ID and IDField = @field and IDVersion = @version and
contains(LongValue, @search)
)
然后使用Intersect方法在LINQ查询中根据需要组合尽可能多的调用:
if (query == null)
{
query = provider.SearchPublications(search.IDVersion, id, string.Format("\"{0}*\"", value));
}
else
{
query = query.Intersect(provider.SearchPublications(search.IDVersion, id, string.Format("\"{0}*\"", value)));
}