2012-04-19 87 views
1

我正在嘗試使用Contains()方法根據傳遞到存儲過程的TSQL參數來搜索全文索引的查詢。包含需要執行prefix_search,因爲它將用於匹配部分單詞(如策略編號的前5個字符)。TSQL參數化CONTAINS

這是我的查詢。

CREATE PROCEDURE [SearchMail] 
(
    @AccountId int, 
    @SearchTerm VARCHAR(100) 
) 
AS 

SET NOCOUNT ON 

    BEGIN 
     SELECT MailId, AccountId, ServerId, ToAddress, FromAddress, DateSent, DateReceived , 
         [Subject], Body, PolicyNumber, ProducerNumber, IsRead, IsDeleted, IsImaged, 
         DateUpdated, DateDeleted, DateImaged, UpdatedBy, DeletedBy, ImagedBy 
     FROM MailMessages 
     WHERE AccountId = @AccountId 
       AND CONTAINS(([Subject], Body, PolicyNumber, ProducerNumber, FromAddress), ' "' + @SearchTerm + '*" ') 
       AND IsDeleted = 0 
       AND IsImaged = 0 
    END 
GO 

但是當我嘗試運行此,企業管理與錯誤迴應:附近有語法錯誤「+」

在這一點上,我不能確定什麼,我可能不正確地做。

回答

2
CREATE PROCEDURE [SearchMail] 
( 
    @AccountId int, 
    @SearchTerm VARCHAR(100) 
) 
AS 

SET NOCOUNT ON 

BEGIN 
    Declare @SearchWithWildcard VARCHAR(200) 
    SET @SearchWithWildcard = '"' + @SearchTerm + '*"' 

    SELECT MailId, AccountId, ServerId, ToAddress, FromAddress, DateSent, DateReceived, 
      [Subject], Body, PolicyNumber, ProducerNumber, IsRead, IsDeleted, IsImaged, 
      DateUpdated, DateDeleted, DateImaged, UpdatedBy, DeletedBy, ImagedBy 
    FROM MailMessages 
    WHERE AccountId = @AccountId 
      AND CONTAINS(([Subject], Body, PolicyNumber, ProducerNumber, FromAddress), 
         @SearchWithWildcard) 
      AND IsDeleted = 0 
      AND IsImaged = 0 
END 
GO 

參考CONTAINS

Specifies a match of words or phrases beginning with the specified text. Enclose a prefix term in double quotation marks ("") and add an asterisk (*) before the ending quotation mark, so that all text starting with the simple term specified before the asterisk is matched. The clause should be specified this way: CONTAINS (column, '"text**"') . The asterisk matches zero, one, or more characters (of the root word or words in the word or phrase). If the text and asterisk are not delimited by double quotation marks, so the predicate reads CONTAINS (column, 'text*') , full-text search considers the asterisk as a character and searches for exact matches to text* . The full-text engine will not find words with the asterisk (*) character because word breakers typically ignore such characters.

+0

我試圖找到任何與搜索關鍵詞開始。因此,例如,如果搜索字詞是'CNM000',我希望它匹配'CNM00'和'CNM0003245' – 2012-04-20 00:06:07