2011-04-26 40 views
4

我在使用sql server全文功能時遇到問題。我正在轉換一些論壇軟件來使用全文搜索,並且我已經安裝和運行了所有內容。我的問題與全文查詢有關。我已經設計了運行根據需要幾個疑問,當我使用CONTAINS謂詞來定位我的搜索結果,如在SQL Server Management Studio中對其進行測試:參數化sql服務器中的全文查詢

Select .... 
From ..... 
WHERE Contains(p.Message,'" dog food "') ...... 

所以這個運行良好,但我怎麼能在準備參數此聲明?我非常希望能夠與運行查詢的WHERE子句,如:

Select .... 
From ..... 
WHERE Contains(p.Message,'" @SearchTerm "') ... 

甚至

WHERE Contains(p.Message,'"@SearchTerm" Near "@OtherSearchTerm") ... 

但這種方法並不因爲雙引號和所有的工作。我可以在代碼中動態構建搜索詞,但出於安全原因,我確實需要爲所有用戶輸入使用參數。我已經看到了數十億谷歌搜索結果,試圖找到一個解決方案,但不能(這肯定會發生在每個人身上,或者我錯過了這裏真正明顯的東西和/或這是不可能的)。有任何想法嗎?

+0

您是否試過使用兩個單引號轉義引號?即:WHERE Con​​tains(p.Message,'@ SearchTerm''Near''@OtherSearchTerm'') – garnertb 2011-04-26 19:25:41

+0

您是否曾經得到過一個確定的答案? – 2011-06-28 15:39:38

回答

0

字符串連接如何?

WHERE Contains(p.Message, '"' + @SearchTerm + '" Near "' + @OtherSearchTerm + '"') 
0

本答案演示了使用Enterprise Library 5.0在VB.NET中進行參數化的SQL Server全文搜索;並進一步顯示每個「對象類型」返回十行(想象人,地點和事物)。

如下表和全文索引:

CREATE TABLE [dbo].[SearchIndexes](
    [SearchIndexId] [int] IDENTITY(1,1) NOT NULL, 
    [ObjectKey] [nvarchar](50) NOT NULL, 
    [ObjectText] [nvarchar](4000) NOT NULL, 
    [CreateDate] [datetime] NOT NULL, 
    [ObjectTypeId] [int] NOT NULL, 
CONSTRAINT [PK_SearchIndexes] PRIMARY KEY CLUSTERED 
(
    [SearchIndexId] ASC 
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 
) ON [PRIMARY] 

GO 

CREATE FULLTEXT INDEX ON [dbo].[SearchIndexes](
[ObjectText] LANGUAGE [English]) 
KEY INDEX [PK_SearchIndexes] ON ([MyDbFullTextCatalog], FILEGROUP [PRIMARY]) 
WITH (CHANGE_TRACKING = AUTO, STOPLIST = SYSTEM) 

代碼:

Public Function FullTextSearch(text As String) As System.Collections.Generic.List(Of String) 

    Const SqlFormat As String = "with RankCte as (select ObjectText, Row_number() over (Partition BY ObjectTypeId ORDER BY ObjectText) AS RowNum FROM dbo.SearchIndexes where contains(ObjectText, @ObjectTextParameter)) SELECT ObjectText FROM RankCte where RowNum <= 10" 
    Const ParameterFormat As String = """{0}*""" 

    Dim db = Databases.MyDb 

    Using command = db.GetSqlStringCommand(SqlFormat) 
    Dim parameterValue = String.Format(Globalization.CultureInfo.InvariantCulture, ParameterFormat, text) 
    'parameterValue should now be something like "search*" (includes the double quotes) 

    db.AddInParameter(command, "ObjectTextParameter", DbType.String, parameterValue) 

    Using reader = db.ExecuteReader(command) 
     Dim results As New List(Of String) 
     Do While reader.Read() 
     results.Add(reader(0).ToString) 
     Loop 
     Return results 
    End Using 
    End Using 
End Function