組 SQL 字串時,加入 WHERE 1=1 條件,以增加組 SQL 字串彈性

若在一般程式語言存取關聯式資料庫,必須要組 SQL 字串,傳至後端的 DB Server,利用 WHERE 1=1,則可把條件句彈性的組合到 SQL 字串中,如下:

strSQL = "select * ";
strSQL +="from employee ";
strSQL +="where 1=1 ";
if(emp_no.length() > 0) {
strSQL +="and emp_no='"+emp_no+"' ";
}
if(emp_name.length() > 0) {
strSQL +="and emp_name='"+emp_name+"' ";
}

上述程式碼動態要將條件語句加入到原本的 SQL 字串中,而不用考慮原本 SQL 字串的格式。

留言

這個網誌中的熱門文章

浴室水龍頭切換拉桿維修

【麵】的倉頡碼

投資現況