当前位置: 代码迷 >> Sql Server >> 存储过程拼模糊查询字符串有关问题
  详细解决方案

存储过程拼模糊查询字符串有关问题

热度:82   发布时间:2016-04-27 17:17:01.0
存储过程拼模糊查询字符串问题

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 "[email protected]+'%"'

end

if @RoleId!='0'

begin

set @str3=' and [email protected]

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 @[email protected][email protected][email protected][email protected]

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语句的引号问题,多谢各位大侠帮忙!

------解决方案--------------------
SQL code
TureName like [email protected]+'%'''
------解决方案--------------------
SQL code
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 [email protected]+'%'''  end if @RoleId!='0' begin set @str3=' and [email protected] 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 @[email protected][email protected][email protected][email protected] print @str5
------解决方案--------------------
动态拼接的话需要转义字符....
'''表示一个'
------解决方案--------------------
SQL code
and TureName like "[email protected]+'%"'--》and TureName like [email protected]+'%'''
  相关解决方案