0

I'm trying to use SQL CONTAINS function with variables. Usually, I can use CONTAINS the following way:

WHERE CONTAINS(tablename, '"some text to search for"')

However, I can't figure out how to insert a variable inside that function that would allow me to search with multiple words.

WHERE CONTAINS(tablename, @Keyword)

only allows to search for one word and will throw an exception if multiple words are passed to it.

Msg 7630, Level 15, State 3, Procedure dbo.bp_SearchCategoryByKeyword, Line 11 [Batch Start Line 0] Syntax error near 'this' in the full-text search condition

9
  • "will throw an exception if multiple words are passed to it" What's the exception? Commented Jan 6, 2020 at 9:58
  • 2
    See this stackoverflow.com/questions/16507239/…. You'll have to split the input and do a JOIN operation. Commented Jan 6, 2020 at 9:58
  • Msg 7630, Level 15, State 3, Procedure dbo.bp_SearchCategoryByKeyword, Line 11 [Batch Start Line 0] Syntax error near 'this' in the full-text search condition 'Check this'. Commented Jan 6, 2020 at 9:59
  • What version of SQL Server? Commented Jan 6, 2020 at 10:00
  • 1
    The accepted answer there uses a WHILE, @KarelFrajták . There are far better options than that for splitting strings, even in (the completely unsupported) SQL Server 2008. Commented Jan 6, 2020 at 10:04

2 Answers 2

2

I just tried this and it worked as expected:

DECLARE @SearchTerms varchar(8000) = 'file AND read';

SELECT MessageID, Description 
FROM dbo.Messages
WHERE CONTAINS(Description, @SearchTerms)
ORDER BY MessageID;

This also worked:

DECLARE @SearchTerms varchar(8000) = '"file" AND "read"';

SELECT MessageID,Description 
FROM dbo.Messages
WHERE CONTAINS(Description, @SearchTerms)
ORDER BY MessageID;
Sign up to request clarification or add additional context in comments.

Comments

0

It is a bit of a hack, but creating a second variable from the first, with double quotes around the first var, will work:

DECLARE @p_searchtermTitle NVARCHAR(255) = '""'
DECLARE @p_searchtermTitle2 NVARCHAR(255) = '""'

SET @p_searchtermTitle = 'The Birth of the World'
SET @p_searchtermTitle2 = '"' + @p_searchtermTitle + '"'

SELECT @p_searchtermTitle, @p_searchtermTitle2, OT.Title
FROM ObjTitles OT 
WHERE CONTAINS(OT.Title, @p_searchtermTitle2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.