使用SQL CONTAINS与变量内的多个单词。

huangapple go评论80阅读模式
英文:

Using SQL CONTAINS with multiple words inside a variable

问题

我正在尝试使用带有变量的SQL CONTAINS函数。通常,我可以按以下方式使用CONTAINS:

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

然而,我无法弄清如何在该函数内插入一个变量,以便允许我搜索多个词语。

WHERE CONTAINS(tablename, @Keyword)

仅允许搜索一个词,并且如果传递多个词,将引发异常。

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
英文:

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

答案1

得分: 2

这部分的翻译如下:

我刚刚尝试了这个,并且它按预期工作了:

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

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

这也有效:

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

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

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;

答案2

得分: 0

这是一个有点巧妙的方法,但是从第一个变量创建第二个变量,用双引号括起第一个变量,将起作用:

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)
英文:

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)

huangapple
  • 本文由 发表于 2020年1月6日 17:55:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定