0
我需要在SQL Server 2008 R2數據庫的1到3個字段中執行子字符串的全文搜索。只有具有非空搜索詞的字段必須被搜索。我使用實體框架,搜索是一個更大的LINQ查詢的一部分,所以它必須在表值函數中進行組合。因此,沒有動態SQL可能。到目前爲止,我想出了以下UDF:從UDF中的查詢中排除WHERE子句的一部分
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
然而,從搜索導致高次優查詢計劃和搜索服用多達10秒才能完成使用@param = @guid or...
結構的排除空參數。沒有所述結構的同樣的搜索幾乎立即返回,但是在那種情況下,我不能使用可變數量的搜索項。當動態SQL不可行時,是否有更優化的方式從查詢中排除部分WHERE子句?爲3個搜索參數的每個組合編寫單獨的TVF是我想避免的。