close

不知道大家有沒有注意

有些程式必須代入SQL撈取的動態資料再顯示成表格

在SQL的語句當中

有時候會看到 where 1= 1 這段

說實話以前我不懂 只是看看就過了

最近我終於開始認真地想要去了解

上網查了幾個網頁

我覺得這個網頁說得最詳細而且好懂

通常都是在where後面有要選擇的狀況下使用

舉例

Sql =    "select top 10 m.name, m.ID "

Sql =     Sql& "from member m where "

              if (age.Text != "")

                  Sql = Sql &“ m.Age=“+“ 'age.Text'“

              enf if

              if (birthday.Text != "")

                  Sql = Sql &“ and m.birthday=“+“ 'birthday.Text'“

              enf if

Response.Write  Sql

上面的例子表示,如果有填入年齡就篩選出年齡相符,如果有填入生日就篩選出生日相符

最後一行則是列出SQL

如果沒有IF判斷式這就是一個完整的SQL

但是有判斷句 所以判斷句裡的SQL可能會出現也可能不會出現

舉個例年齡沒有填(Null) 有年出生年月日(20170602)

最後一行輸出SQL就會變成

「select top 10 m.name, m.ID from member m where and m.birthday = '20170602'」

上述兩個條件都不符合,沒有填年齡也沒填出生年月日

最後一行輸出SQL就會變成

「select top 10 m.name, m.ID from member m where

有沒有發現 上述兩個例子都無法成為一個完整的SQL

這種時候就會發生錯誤

所以才要加上Where 1=1 或 Where 1=0

一方面可以不用考慮後面條件成立時如果是第一個會多出一個and

一方面所有條件都不成立時也不會出錯

1=1、跟1=0有點像布林值 1=1為True,1=0為false

通常1=0是用在不論甚麼條件都不顯示的情況

所以我們這邊是用1=1

Sql =    "select top 10 m.name, m.ID "

Sql =     Sql& "from member m where 1=1 "

              if (age.Text != "")

                  Sql = Sql &“ and m.Age=“+“ 'age.Text'“

              enf if

              if (birthday.Text != "")

                  Sql = Sql &“ and m.birthday=“+“ 'birthday.Text'“

              enf if

Response.Write  Sql

此時再試試年齡沒有填(Null) 有年出生年月日(20170602)

最後一行輸出SQL會變成

「select top 10 m.name, m.ID from member m where 1=1 and m.birthday = '20170602'」

兩個條件都不符合時

「select top 10 m.name, m.ID from member m where 1=1」

不論甚麼條件都不會影響SQL的完整性,就不會出錯囉!

 

 

arrow
arrow
    文章標籤
    SQL 教學 筆記
    全站熱搜

    D.D 發表在 痞客邦 留言(0) 人氣()