SQL 中的多条件查询

时间:2023-03-08 23:10:27
SQL 中的多条件查询

在应用程序开发中,多条件查询是个经常遇到的情况,最简单最麻烦的方法是把所有的可能情况都考虑到,但是无疑是繁琐的,而且很容易漏掉可能的情形,下面是SQL语句实现多条件查询的情况

select *
from table
where table .a=case when isnull(a,'')!='' then a else table .a end
and table .b=case when isnull(b,'')!='' then b else table .b end
and table .c=case when isnull(c,'')!='' then c else table .c end
and table .d=case when isnull(d,'')!='' then d else table .d end

当查询条件a,b,c,d某个为空的时候,由于isnull的存在,会被替换为'',。

上面的程序需要注意的是两点:

(1)case的使用方法

(2)null的使用方法

这两个函数在SQL中都有详细的介绍,不再赘述!


Searched CASE function:
CASE
     WHEN Boolean_expression THEN result_expression
    [ ...n ]
     [
    ELSE else_result_expression
     ]
END

使用指定的替换值替换 NULL。

ISNULL ( check_expression , replacement_value )

需要注意的是check_expression可以隐式转换为replacement_value