本文主要參考 和
現在進入正題:
加入where 1=1,既是where 的條件成立,為永真,得到的結果就是未加約束條件的。為了動態sql中連線and條件。
where後面總要有語句,加上了1=1後就可以保證語法不會出錯!
假如後面確定有條件語句,就可以不用1=1;
不能確定where後面是否有語句的時候就要加上1=1了,當沒有其他條件語句時候,還有1=1,就不會輸錯了 。
例1:sql="select * from table where 1=1 "&where_str
where_str是根據前面填入的得到的乙個串.這樣就不用管是否為空,都不會出現錯誤.就這點技巧了。
就是說:1=1永真條件,一般用於構造動態sql語句,"select ... from ... where 1=1 "+動態構造條件子句。
如果不寫1=1呢,那麼在每乙個不為空的查詢條件面前,都必須判斷有沒有where字句,否則要在第乙個出現的地方加where
if(!name.equals(""))
if(!age.equals(""))
if(!height.equals(""))
if(!weight.equals(""))
where 1=1的寫法是為了檢化程式中對條件的檢測
例2:打個比方有三個引數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;
例3:
string sql = "select * from " + db_tablename + " where 1=1 and (name like '%" + condition + "%' " +
"or mobilephone like '%" + condition + "%' or familyphone like '%" + condition + "%' " +
"or officephone like '%" + condition + "%')" + strselection;
加上where 1=1 之後,就可以直接使用and 和or 語句了,不怕出現語法錯誤了~~~
2016.1.19晴,冷,心情little down~
Sql語句中的DDL語句
資料庫模式定義語言ddl data definition language 是用於描述資料庫中要儲存的現實世界實體的語言。主要由create 新增 alter 修改 drop 刪除 和 truncate 刪除 四個關鍵字完成。create database 資料庫名 建立乙個資料庫 create d...
深入理解SQL表連線(join)
關聯式資料庫中最重要的兩個概念,當屬表連線和聚合。表連線將一條資料分開成多條,表聚合將多條合成一條。這一分一合,形成了關聯式資料庫強大的邏輯表達能力,這篇文章講表連線,關於聚合請移步 深入理解sql分組聚合 內連線 外連線 左外連線 右外連線 全連線 交叉連線 自然連線 這麼多種連線方式,你是不是已...
深入理解SQL多表聯結的原理
聯結多個表 直接上去擼 select prod name,vend name,prod price,quantity from orderitems,products,vendors where products.vend id vendors.vend id and orderitems.prod...