存储过程拼模糊查询字符串问题
declare @indextable table(id int identity(1,1),nid int)
set rowcount 1
declare @TureName varchar(50)
declare @RoleId varchar(2)
set @RoleId='1'
set @TureName='三'
declare @str1 varchar(500)
declare @str2 varchar(500)
declare @str3 varchar(500)
declare @str4 varchar(500)
declare @str5 varchar(5000)
set @str1='insert into @indextable(nid) select UserId from Users where 1=1'
if @TureName!=''
begin
set @str2= ' and TureName like "%'+@TureName+'%"'
end
if @RoleId!='0'
begin
set @str3=' and RoleId='+@RoleId
end
set @str4= ' order by CreateTime desc
select * from ProgramInfo O,@indextable t where O.Id=t.nid
and t.id between 1 and 1 order by t.id'
set @str5=@str1+@str2+@str3+@str4
print @str5[color=#FF6600][/color]
这是测试存储过程,结果为:
insert into @indextable(nid) select UserId from Users where 1=1 and TureName like "%三%" and RoleId=1 order by CreateTime desc
select * from ProgramInfo O,@indextable t where O.Id=t.nid
and t.id between 1 and 1 order by t.id
请问如何将"%三%" 变成单引号。很难搞懂存储过程里拼接sql语句的引号问题,多谢各位大侠帮忙!
[解决办法]
TureName like ''%'+@TureName+'%'''
[解决办法]
declare @indextable table(id int identity(1,1),nid int) set rowcount 1 declare @TureName varchar(50) declare @RoleId varchar(2) set @RoleId='1' set @TureName='三' declare @str1 varchar(500) declare @str2 varchar(500) declare @str3 varchar(500) declare @str4 varchar(500) declare @str5 varchar(5000) set @str1='insert into @indextable(nid) select UserId from Users where 1=1' if @TureName!='' begin set @str2= ' and TureName like ''%'+@TureName+'%''' end if @RoleId!='0' begin set @str3=' and RoleId='+@RoleId end set @str4= ' order by CreateTime desc select * from ProgramInfo O,@indextable t where O.Id=t.nid and t.id between 1 and 1 order by t.id' set @str5=@str1+@str2+@str3+@str4 print @str5
[解决办法]
动态拼接的话需要转义字符....
'''表示一个'
[解决办法]
and TureName like "%'+@TureName+'%"'--》and TureName like ''%'+@TureName+'%'''