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 を作成することは避けたいと思います。