今天开发程序时遇到一个问题,我负责前台调用另一个同事写的后台查询方法。我只需要将查询值传给查询方法即可。
表中只有三个字段,表结构如下
| deptno | deptname | descript |
| 1 | aa | 无 |
| 2 | bb | NULL |
deptno、deptname、descript三个字段都是查询条件(也就是where条件)
页面只输入了部门编号是2,其他两列没有值,则为空。
查询sql是 select * from dept where deptno like '%2%' and deptname like '%%'and descript like '%%'
因为用户只要找编号是2的记录,其他条件没有输入,而数据库也有这条记录,按理说应该能查询出来,但是因为descript是NULL,使用like '%%'无法查出NULL的记录,所以就没有查询出。
其实正确的处理方式应该是拼接sql
string sql = "select * from dept where 1=1";
if(deptno != "")
{
sql+= "and deptno like '%'"+deptno+"'%' ";
}
else if(deptname != "")
{
sql+= "and deptnamelike '%'"+deptname+"'%' ";
}
else if(descript != "")
{
sql+= "and descriptlike '%'"+descript+"'%' ";
}
另一种解决方法是利用isnull函数,但因为效率问题还是不赞成使用第二种方法
select * from dept where deptno like '%2%' and isnull(deptname,'') like '%%'and isnull(descript,0) like '%%'
本文探讨了一个在SQL查询中遇到的难题:如何正确处理NULL值以确保其在查询条件中被正确匹配。通过实例展示了如何避免使用like'%%'与isnull函数的效率问题,并提供了一种更灵活的字符串拼接方法来构建SQL查询。
2727

被折叠的 条评论
为什么被折叠?



