我有以下SQL查询用于搜索目的。
有一个@st
变量,它被分配了一个SQL查询,最后我将执行查询。问题是为@st
变量分配了一个字符串(这是查询),在字符串中有LIKE
表达式,例如:
address like '%edmon%'
所以它变成了:
set @st='select * from infoone where address like '%edmon%''
它导致错误:
edmon附近的语法错误
完整查询如下,
declare @v int;
declare @st varchar(1000);
set @st = 'select PLACEID, LEFT(CONVERT(NVARCHAR(1000), description), 500) as
des1, LOCATIONCITY, ADDRESS, DateT, RENT from infoone where ';
Select @v = count(address)
from infoone
where ((address like '%main%') OR (address like '%main street%')
OR (address like '%main street edmonton%'));
if @v>0
begin
set @st = @st + '(address like '%main%') OR
(address like '%main street%') OR
(address like '%main street edmonton%')' +
'and (';
end
else begin
execute(@st)
请让我知道我做错了什么以及如何解决它
由于
答案 0 :(得分:4)
要在字符串上获取单引号,请使用''
:
set @st = 'select * from infoone where address like ''%edmon%'''
答案 1 :(得分:0)
Gordon Linoff已经向您解释了您的单引号'
出错的地方,但您的陈述还有其他一些问题。做你想做的更好的方法就是这样......
declare @st nvarchar(MAX);
set @st=N' select PLACEID
,CONVERT(NVARCHAR(500),[description]) as des1
,LOCATIONCITY
,[ADDRESS]
,DateT
,RENT
from infoone where 1 = 1 ';
IF EXISTS (Select * from infoone
where(([ADDRESS] like '%main%')
OR ([ADDRESS] like '%main street%')
OR ([ADDRESS] like '%main street edmonton%')))
begin
set @st = @st+ N' AND (
([ADDRESS] like ''%main%'')
OR
([ADDRESS] like ''%main street%'')
OR
([ADDRESS] like ''%main street edmonton%'')
)';
end
else
begin
set @st = @st+ N' AND (Some Other Condition) )'
end
EXECUTE sp_executesql @st