sql语句中where 1=1的作用

where 1=1 
最近看到很多sql里用到where 1=1,原来觉得这没用嘛,但是又想到如果没用为什么要写呢?于是在网上 

查了查,在这里就浅谈一下: 
1=1 永真, 1<>1 永假。 

1<>1 的用处: 
用于只取结构不取数据的场合 
例如: 
create table table_temp tablespace tbs_temp as 
select * from table_ori where 1<>1 
建成一个与table_ori 结构相同的表table_temp,但是不要table_ori 里的数据。(除了表结构,其它结 

构也同理) 

1=1的用处 
用于动态SQL 
例如 lv_string := 'select tbl_name,tbl_desc from tbl_test where 1=1 '||l_condition; 
当用户选择了查询的名称'abc'时l_condition :='and tbl_name = ''abc'''';但是当用户没有 

选择名称查询时l_condition就为空 这样 lv_string = 'select tbl_name,tbl_desc from tbl_test 

where 1=1 ' ,运行也不会出错,相当于没有限制名称条件。但是如果没有1=1的条件,则lv_string = 

'select tbl_name,tbl_desc from tbl_test where ';这样就会报错。 

除了1=1 或1<>1之外的其它永真永假的条件同理。

----------------------------------------------

where 1=1;有什么用?在SQL语言中,这个条件始终为True,写这一句话就跟没写一样。select * from table where 1=1与select * from table完全没有区别,其目的就是使 where 的条件永远为true,得到的结果就是未加约束条件的结果。
在查询条件数量不确定的条件情况下,使用 where 1=1可以很方便的规范语句。例如一个查询中可能有name,age,height,weight等不确定数量的约束条件,那么使用
String sql="select * from table where 1=1";
if(!name.equals("")){
sql=sql+"and/or name='"+name+"'";
}
if(!age.equals("")){
sql=sql+"and/or age'"+age+"'";
}
if(!height.equals("")){
sql=sql+"and/or height='"+height+"'";
}
if(!weight.equals("")){
sql=sql+"and/or weight='"+weight+"'";
}

如果不写1=1,那么在每一个不为空的查询条件面前,都必须判断有没有where字句,哪里该加where,哪里该加and/or
用上 where 1=1 之后,就不存在这样的问题, 条件是 and 就直接and ,是or就直接接 or

完全复制表 
create   table_name   as   select   *   from   Source_table   where   1=1; 

复制表结构 
create   table_name   as   select   *   from   Source_table   where   1=0;

猜你喜欢

转载自blog.csdn.net/LMAKE_nbsp/article/details/84113036