2012-04-19 4 views
1

J'essaie de résoudre une requête qui utilise la méthode Contient() pour rechercher un index de texte intégral basé sur un paramètre TSQL passé dans la procédure stockée. Le Contient doit faire un prefix_search car il sera utilisé pour faire correspondre des mots partiels (tels que les 5 premiers caractères d'un numéro de police).TSQL Parameterized CONTAINS

Ceci est ma requête.

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 

Mais quand je tente d'exécuter cela, Enterprise Manager répond avec une erreur: Syntaxe incorrecte près de « + »

À ce stade, je ne suis pas sûr ce que je peux être en train de faire mal.

Répondre

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 

Ref 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

J'essaie de trouver quelque chose qui commence par le searchTerm. Par exemple, si le terme de recherche est 'CNM000', je voudrais qu'il corresponde à 'CNM00' et 'CNM0003245' –