在数据库编程中,管理人员需要经常从数据库中查询数据。当查询条件为确定时,我们可以明确用的sql语句来实现,但是当查询条件为多个条件的动态组合时,查询语句会由于分支太多及if语句的多重嵌套而变得相当复杂。在此,笔者提供了一种优化方法,运用本方法可以有效地减少查询语句的分支和数量以及if条件语句的嵌套层数,从而提高程序的运行效率。
下面我们以一个简单的例子来说明,假设有一个名为employee的表,现在我们要从其中查询数据,条件有三个,由用户动态选择,如图1所示:
其中条件a、b、c之间是与的关系,a、b、c均为动态选择,可以取其中的一个、两个或三个,也可以一个都不选,当三个条件都不选择时则认为是无条件查询,按照通常的做法,判断方法如图2所示:
这样,最终的结果有8个,即有8条查询语句,分别是
1.select * from employee;
2.select * from employee where age =c ;
3.select * from employee where sex=b;
4.select * from employee where sex=b and age=c;
5.select * from employee where name=a;
6.select * from employee where name=a and age=c;
7.select * from employee where name=a and sex=b ;
8.select * from employee where name=a and sex=b and age=c;
显然这是比较烦琐的,而且用到了多重嵌套if语句,因而在条件增多时,其复杂程度将大大增加。我们对它进行优化,方法如下:
首先定义一个字符串str_result用来存放组合条件的结果,开始时为空。
用程序语言描述如下:
| if a <> "" then str_result="where name =a" end if if b <> "" then if str_result="" then str_result="where sex=b" else str_result=str_result+"and sex = b" end if end if if c <> "" then if str_result="" then str_result="where age =c" else str_result=str_result+"and age=c" end if end if |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器