这是一个例子,我有这段代码的动态版本。
这让我觉得你在使用一个变量...我在下面解释一下
但是,此代码在本地运行良好,但在主机上运行不正常!
无论您在 SQL Server 2008、2012、2016 等中运行,此代码都不会提供不同的结果...
我的本地sql server是2014,宿主sql server是2012
这无关紧要,除非数据不同(未镜像/复制)
如果此代码在 sql server 2012 上不起作用,我应该使用什么代码
精确搜索?
您说“它不起作用”。如果您想要“精确”,那么您只使用 = 运算符...而不是 LIKE 函数。
WHERE TakhfifName = 'keyword'
--or if you have a variable
WHERE TakhfifName = @keyword
要么您实际上是在尝试搜索工作 keyword,但它显然不存在,或者您不确定如何在 SQL Server 中正确使用 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