我有这个问题:
SELECT * FROM Takhfif WHERE TakhfifName LIKE '%keyword%' AND CityID=2
这是一个例子。我有这段代码的动态版本。
此代码在本地运行良好,但在主机中无效!
我的本地SQL Server是2014 主机SQL Server是2012。
如果此代码在SQL Server 2012上不起作用,我应该使用哪些代码进行精确搜索?
答案 0 :(得分:0)
这是一个示例,我有此代码的动态版本。
这让我觉得你正在使用变量......我在下面解释
但是这段代码在本地工作得很好,但在主机上没有工作!
如果您在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
答案 1 :(得分:0)
要考虑的事情
尝试使用周围空格的关键字。
SELECT * FROM Takhfif WHERE TakhfifName LIKE ' %keyword% ' AND CityID=2
SELECT * FROM Takhfif WHERE TakhfifName LIKE '% keyword %' AND CityID=2
希望这会有所帮助