where 1=1 是一个永远为true的表达式。在不定数量查询条件下,1=1 可以非常方便的规范语句。
string sql = “select * from tablename where ";
if(Age.Text.Lenght > 0){
sql = sql +“Age=“+“'Age.Text'“;
}
if(Address.Text.Lenght>0){
sql = sql +“and Address=“+“'Address.Text'“;
}
当第一个和第二个if都是true的时候,一切正常。sql语句变成
select * from tablename where Age = ” ” and Address = “” ;
如果第一个sql为false的时候。sql语句变成,
select * from tablename where and Address = “” ;
或者两个sql都为false的时候,sql语句变成
select * from tablename where ;
所以很糟糕。因为这是一个错误的sql,没有结果返回。
使用了where 1= 1后
string sql = “select * from tablename where 1 =1 “;
if(Age.Text.Lenght > 0){
sql = sql +“and Age=“+“’Age.Text’“;
}
if(Address.Text.Lenght>0){
sql = sql +“and Address=“+“’Address.Text’“;
}
如果两个if都是true, sql语句变成:
select * from tablename where 1= 1 and Age = ” ” and Address = “” ;
如果第一个if为false,sql语句变成:
select * from tablename where 1=1 and Address = “” ;
如果两个if都是false。sql语句变成:
select * from tablename where 1=1 ;
where 1=1 不是什么高级的应用,也不是所谓的智能化的构造,仅仅只是为了满足多条件查询页面中不确定的各种因素而采用的一种构造一条正确能运行的动态SQL语句的一种方法。
where 1 = 0 是永远为false的一个判断条件。结果不会返回任何数据,只有表结构,可用于快速建表。
select * from tablename where 1=0;
这时候即使表中有数据,也不会返回,只返回表结构。Empty set 空结果集。
可以使用此语句进行快速创表。
create table newtable as select * from oldtable where 1=0;
创建一个新表,而新表的结构与查询的表结构是一样。