sql 模糊查询like 如何处理 NULL

来源:互联网 发布:mac 提醒事项 红点 编辑:程序博客网 时间:2024/05/29 12:29

今天开发程序时遇到一个问题,我负责前台调用另一个同事写的后台查询方法。我只需要将查询值传给查询方法即可。

表中只有三个字段,表结构如下

deptnodeptnamedescript1aa无2bbNULL

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 '%%'

0 0
原创粉丝点击