2012-04-19 88 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