where 1=1的用處

  where 1=1有什麼用?在SQL語言中,寫這麼一句話就跟沒寫同樣。

  select * from table1 where 1=1與select * from table1徹底沒有區別,甚至還有其餘許多寫法,1<>2,'a'='a','a'<>'b',其目的就只有一個,where 的條件爲永真,獲得的結果就是未加約束條件的。sql

在SQL注入時會用到這個,例如select * from table1 where name='lala'給強行加上select * from table1 where name='lala' or 1=1這就又變成了無約束的查詢了。spa

  最近發現的妙用在於,在不定數量查詢條件狀況下,1=1能夠很方便的規範語句。例如一個查詢可能有name,age,height,weight約束,也可能沒有,那該如何處理呢?code

String sql=select * from table1 where 1=1it

爲何要寫多餘的1=1?立刻就知道了。table

代碼以下:

if(!name.equals("")){
sql=sql+"name='"+name+"'";
}
if(!age.equals("")){
sql=sql+"age'"+age+"'";
}
if(!height.equals("")){
sql=sql+"height='"+height+"'";
}
if(!weight.equals("")){
sql=sql+"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是否爲空進行檢測class

用上 where 1=1 以後,就不存在這樣的問題, 條件是 and 就直接and ,是or就直接接 orselect

拷貝表 
create   table_name   as   select   *   from   Source_table   where   1=1;程序

複製表結構 
create   table_name   as   select   *   from   Source_table   where   1 <> 1;demo

相關文章
相關標籤/搜索