Asp.net下多条件查询的办法

来源:互联网 发布:博弈软件 编辑:程序博客网 时间:2024/05/01 09:40
第一种方式:
写一个存储过程,将所有的条件作为参数(如@case1,   @case2...)传入,当某个条件为空的时候,传入Convert.DbNull即可
在存储过程中的SQL语句的Where条件中,以
字段1   =   isnull(@case1,   字段1)   and   字段2   =   isnull(@case2,   字段2)   and   ...
的形式列出所有条件即可

例1:
select * from test  where test1 = '1' and test2 = '2' and test3 = '3'
结果:
test1                                              test2                                              test3
--------------------------- -------------------------------------------- ----------------------
1                                                  2                                                  3         
1                                                  2                                                  3         
(2 行受影响)
--------------------------------------------

declare @param1 varchar(10)
declare @param2 varchar(10)
declare @param3 varchar(10)

set @param1 = '1'
set @param1 = '2'
set @param1 = '3'

select * from test where test1 = isnull(@param1, '1')
and test2 = isnull(@param2, '1') and test3 = isnull(@param3, '1')

第二种方式:
可以将所有查询条件做为一个实体对象传递到DAL层,然后通过通过判断各种条件是否为空来构造SQL语句

例:
str   sql   =   "select   *   from   tb_student   where   1=1";
 
if(checkbox1.checked)
        sql 
+=   " and   StuName   like   '%"+text1.Text+"%'   ";
 
if(checkbox2.checked)  
        sql 
+=   " and   StuID   like   '%"+text2.Text+"%'   ";
 
if(checkbox3.checked)  
        sql  
+=  " and   StuADD   like   '%"+text3.Text+"%'   ";