LIKE 命令在主机上不起作用

LIKE command not working on host

我有这个查询:

SELECT * FROM Takhfif WHERE TakhfifName LIKE '%keyword%' AND CityID=2

这是一个例子。我有此代码的动态版本。

此代码在本地运行良好,但在主机上运行不佳!

我的本地SQL服务器是2014 主机 SQL 服务器是 2012.

如果此代码在 SQL Server 2012 上不起作用,我应该使用什么代码进行精确搜索?

this is an example i have dynamic version of this code.

这让我觉得你在使用变量...我在下面解释

However this code is working great on local but not working in host!

无论您是否在 SQL 服务器 2008、2012、2016 等中 运行,此代码都不会提供不同的结果...

my local Sql Server is 2014 and the host sql server is 2012

这没关系,除非数据不同(未镜像/复制)

if this code not working on sql server 2012 what code should i use for a exact search?

你说 "it isn't working"。如果你想要 "exact" 那么你只使用 = 运算符......而不是 LIKE 函数。

WHERE TakhfifName = 'keyword'
--or if you have a variable
WHERE TakhfifName = @keyword

要么你真的在尝试搜索作品 keyword 但它显然不存在,要么你不确定如何使用 SQL 中的 LIKE 功能服务器正确。考虑这些例子...

declare @Takhfif table (TakhfifName varchar (64), CityID int)
insert into @Takhfif (TakhfifName, CityID) values
('United States',1),
('China',1),
('Russia',1),
('Brazil',1),
('France',1),
('Japan',2),
('Morocco',2)

--This query will return records where CityID = 1 and the letters ra are located anywhere in the TakhfifName
SELECT * 
FROM @Takhfif 
WHERE TakhfifName LIKE '%ra%' AND CityID=1

--This query will return records where CityID = 1 and the letter a is located at the END of the name
SELECT * 
FROM @Takhfif 
WHERE TakhfifName LIKE '%a' AND CityID=1

--This query will return records where CityID = 1 and the letter C is located at the beginning of the name
SELECT * 
FROM @Takhfif 
WHERE TakhfifName LIKE 'c%' AND CityID=1

-----------------------------------------------------------------------------
--If you want to use these with a variable, you have to use concatonation
-----------------------------------------------------------------------------

declare @variable varchar(16)

set @variable = 'ra'
--This query will return records where CityID = 1 and the letters ra are located anywhere in the TakhfifName
SELECT * 
FROM @Takhfif 
WHERE TakhfifName LIKE '%' + @variable + '%' AND CityID=1

set @variable = '%a'
--This query will return records where CityID = 1 and the letter a is located at the END of the name
SELECT * 
FROM @Takhfif 
WHERE TakhfifName LIKE '%' + @variable AND CityID=1

set @variable = 'c%'
--This query will return records where CityID = 1 and the letter C is located at the beginning of the name
SELECT * 
FROM @Takhfif 
WHERE TakhfifName LIKE @variable + '%' AND CityID=1

需要考虑的事项

  1. 正在搜索列中的单个关键字。(关键字 1、关键字 2、关键字 3)
  2. 在列中的字符串中搜索关键字(查找此关键字 1 在一个句子)

尝试用 space 包围您的关键字。

SELECT * FROM Takhfif WHERE TakhfifName LIKE ' %keyword% ' AND CityID=2
SELECT * FROM Takhfif WHERE TakhfifName LIKE '% keyword %' AND CityID=2

希望这对您有所帮助