sql 模糊查詢like 如何處理 NULL

今天開發程序時遇到一個問題,我負責前臺調用另一個同事寫的後臺查詢方法。我只需要將查詢值傳給查詢方法即可。

表中只有三個字段,表結構如下

deptno deptname descript
1 aa
2 bb NULL

deptno、deptname、descript三個字段都是查詢條件(也就是where條件)

頁面只輸入了部門編號是2,其他兩列沒有值,則爲空。

查詢sql是 select * from dept where deptno like '%2%'  and deptname like '%%'and descript like '%%'

因爲用戶只要找編號是2的記錄,其他條件沒有輸入,而數據庫也有這條記錄,按理說應該能查詢出來,但是因爲descript是NULL,使用like '%%'無法查出NULL的記錄,所以就沒有查詢出。

其實正確的處理方式應該是拼接sql

string sql = "select * from dept where 1=1";

if(deptno != "")

{

     sql+= "and deptno like '%'"+deptno+"'%' ";

}

else if(deptname != "")

{

   sql+= "and deptnamelike '%'"+deptname+"'%' ";

}

else if(descript != "")

{

   sql+= "and descriptlike '%'"+descript+"'%' ";

}

 

另一種解決方法是利用isnull函數,但因爲效率問題還是不贊成使用第二種方法

select * from dept where deptno like '%2%'  and isnull(deptname,'') like '%%'and isnull(descript,0) like '%%'

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章