多條件查詢生成sql語句
剛來公司,要做一個增刪改查的功能,其中涉及到多條件查詢。對於多條件查詢,主要是涉及到如何生成sql的問題
-
在前台用js判斷是否輸入參數,把參數拼接成一個查詢條件(有2*n個分支選擇),然后傳入后台拼接成一條sql語句,如:
function getQueryParameters(){ var params = "where"; var house_id = document.getElementById("house_search_id").value; var house_name = document.getElementById("house_search_name").value; var house_location = document.getElementById("house_search_location").value; if(house_id != ""){ if(params == "where") params = params + " id = " + house_id; else params = params + " and " + " id = " + house_id; } if(house_name != ""){ if(params == "where") params = params + " name like '" + house_name + "%' "; else params = params + " and " + " name like '" + house_name + "%' "; } if(house_location != ""){ if(params == "where") params = params + " location like '" + house_location + "%' "; else params = params + " and " + " location like '" + house_location + "%' "; } if(params == "where") params = ""; document.getElementById("queryParam").value = params; //添加查詢參數 docuemnt.getElementById("queryParam_fistPage").value = params; document.getElementById("queryParam_prePage").value = params; document.getElementById("queryParam_nextPage").value = params; document.getElementById("queryParam_lastPage").value = params; document.getElementById("queryParam_edit").value = params; //上面這段主要是為了在查詢以后,輸入框中任然存在搜索條件,其實這么寫就可以了 /***************************************************************************************** <%String param = request.getParameter("param")!= null ? "" :request.getParameter("param");%> <input type="text" name="param" value="<%=param%>" ****************************************************************************************/
}
-
把所有的查詢條件都以一個不會改變查詢結果的默認值寫上,當傳入的參數不為空的時候,就把默認值替換掉
select * from table where field1 = case when @param1 <> '-全部-' then @param else field1 and field2 = case when @param2 <> '-全部-' then @param else filed2;
有時間實現下第二種方法,干凈多了;