where 1=1有什么用?在SQL語言中,寫這么一句話就跟沒寫一樣。
select * from table1 where 1=1與select * from table1完全沒有區別,甚至還有其他許多寫法,1<>2,'a'='a','a'<>'b',其目的就只有一個,where 的條件為永真,得到的結果就是未加約束條件的。
在SQL注入時會用到這個,例如select * from table1 where name='lala'給強行加上select * from table1 where name='lala' or 1=1這就又變成了無約束的查詢了。
最近發現的妙用在于,在不定數量查詢條件情況下,1=1可以很方便的規范語句。例如一個查詢可能有name,age,height,weight約束,也可能沒有,那該如何處理呢?
String sql=select * from table1 where 1=1
為什么要寫多余的1=1?馬上就知道了。
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
拷貝表
create table_name as select * from Source_table where 1=1;
復制表結構
create table_name as select * from Source_table where 1 <> 1;
新聞熱點
疑難解答