http://xiangai.taobao.com
http://shop148612228.taobao.com

sql where 1=1 妙用之一方面

在不定数量查询条件情况下,1=1可以很方便的规范语句。例如一个查询可能有name,age,height,weight约束,也可能没有,那该如何处理呢?

String sql=select * from table1 where 1=1

为什么要写多余的1=1?马上就知道了。

if(!name.equals("")){
sql=sql+"and name='"+name+"'";
}
if(!age.equals("")){
sql=sql+"and age'"+age+"'";
}
if(!height.equals("")){
sql=sql+"and height='"+height+"'";
}
if(!weight.equals("")){
sql=sql+"and weight='"+weight+"'";
}

如果不写1=1呢,那么在每一个不为空的查询条件面前,都必须判断有没有where字句,否则要在第一个出现的地方加where

where 1=1的写法是为了检化程序中对条件的检测
打个比方有三个参数a, b, c
@sql=select * from tb'
这三个参数都可能为空
这时你要构造语句的话,一个个检测再写语句就麻烦
比如
if @a is not null
@sql=@sql + " where a=' + @a
if @b is not null
这里你怎么写?要不要加where 或直接用 and ?,你这里还要对@a是否为空进行检测

用上 where 1=1 之后,就不存在这样的问题, 条件是 and 就直接and ,是or就直接接 or

posted @ 2012-02-20 12:07  万事俱备就差个程序员  阅读(311)  评论(0编辑  收藏  举报

http://xiangai.taobao.com
http://shop148612228.taobao.com
如果您觉得对您有帮助.领个红包吧.谢谢.
支付宝红包
微信打赏 支付宝打赏