积少成多 ---- 仅以此致敬和我一样在慢慢前进的人儿
问题: 在sqlserver 进行模糊查询,出现问题
最初使用“concat”,进行拼串 *** 作,如下所示:
<select ID = "queryCount" resultType="int" > select count(*) from t_user <where> <if test = "queryText!= null"> loginacct like concat("%",#{queryText},"%) </if> </where></select>
运行结果:“concat” 是不是可以识别的函数,不是内置函数
查询结果: “concat”方法进行拼串,只适用于MysqL 和 oracle,不适用于sqlserver,这个函数是用来连接字符串, sqlserver中没有,可以使用 + 连接符号搞定
解决方案:使用传统的拼串 *** 作,“like” *** 作尝试:
尝试一: 使用占位符(#{})
<select ID = "queryCount" resultType="int" > select count(*) from t_user <where> <if test = "queryText!= null"> loginacct like ‘%#{queryText}%‘ </if> </where></select>
运行结果:
Preparing: select count(*) from t_user WHERE loginacct like ‘%?%‘
com.microsoft.sqlserver.jdbc.sqlServerException: 索引 1 超出范围。
查询结果:在使用占位符进行模糊查询时不能把问号放在引号里面,问号的位置必须跟字段名同级;(不理解)
解决方案:like ‘%‘ + #{quertText} + ‘%’(成功运行)
<select ID = "queryCount" resultType="int" >
select count(*)
from t_user
<where>
<if test = "queryText!= null"> loginacct like ‘%‘ + #{queryText}+ ‘%‘ </if>
</where>
</select>
尝试二: 使用EL表达式(成功运行) <select ID = "queryCount" resultType="int" > select count(*) from t_user <where> <if test = "queryText!= null"> loginacct like ‘%${queryText}%‘ </if> </where> </select>
存在问题:使用 ${}无法防止sql注入
结论:sqlserver 模糊查询中, 优先使用 like ‘%‘ + #{quertText} + ‘%’进行 *** 作
sqlserver 分页模糊查询例码:(供自己忘记后查看)
<select ID = "queryList" resultType="T_user"> select top ${pagesize}* from t_user <where> <if test = "queryText!=null">loginacct like ‘%‘ + #{queryText}+ ‘%‘ and ID not in (select top ${startIndex} ID from t_user order by ID) order by ID </if> </where> <where> <if test = "queryText==null"> ID not in (select top ${startIndex} ID from t_user order by ID) order by ID </if> </where></select>总结
注意事项: 单个或者是多个条件查询,都是只有一个“where” 条件之间使用 “and” 连接
以上是内存溢出为你收集整理的sqlserver 分页模糊查询全部内容,希望文章能够帮你解决sqlserver 分页模糊查询所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)