剛剛學C#不久,現在正在修改一個ASP.NET系統。碰到一個問題:在查詢頁面上,有5個查詢條件,可以5個查詢條件自由組合,這樣的話就有
1 2 3
C5 + C5 + C5 = 25種組合,如果簡單的使用分支語句去寫,將會把代碼搞得很冗餘,而且容易出錯。於是想了一個較簡單的演算法去實現。演算法思想如下:
定義兩個數組,一個是標誌位元組,一個是查詢條件數組,只要發生查詢條件的,標誌位就標為1,遍曆查詢條件後,使用一個for語句遍曆標誌位,把有標誌位對應的查詢條件的SQL語句組合起來,然後再整合出最後的查詢語句。
具體代碼如下:
string drp = this.drpFlow.SelectedItem.Text;
string user=this.drpUser.Text;
string date=this.txtDate.Text;
string title = this.txtTitle.Text;
string sys = this.sysFlow.SelectedItem.Text;
int[] tt = new int[5] ;
string temp = ""; //定義臨時字串存放合并字串
string strSql = "select * from Fault where State=0";
string strSql2 = " ORDER BY RecDate DESC";
string strSql3 = " and Department='" + drp + "'";
string strSql4 = " and RecMen='" + user + "'";
string strSql5 = " and RecDate='" + date + "'";
string strSql6 = " and SysClass='" + sys + "'";
string strSql7 = " and FirstFault like '%" + title + "%'" + " or NowFault like '%" + title + "%'" +" or TryWay like '%" + title + "%'" +" or Other like '%" + title + "%'" ;
//定義查詢條件數組
//tt[0] tt[1] tt[2] tt[3] tt[4]
//drp user date sys title
//strSql3 strSql4 strSql5 strSql6 strSql7
int[] tt = new int[5];
//定義字串資料,存放相關的SQL字串
string[] sqlarry = new string[5] { strSql3, strSql4, strSql5, strSql6, strSql7 };
//
if (!this.drpFlow.SelectedItem.Text.Equals("請選擇部門"))
{
tt[0] = 1;
}
//if (!this.drpUser.Text.Equals("請選擇人員"))
if(user != "")
{
tt[1] = 1;
}
//if (!date.Equals(""))
if(date != "")
{
tt[2] = 1;
}
if (!this.sysFlow.SelectedItem.Text.Equals("所屬系統"))
{
tt[3] = 1;
}
//if (!title.Equals(""))
if(title != "")
{
tt[4] = 1;
}
//for語句整合有條件輸入的SQL語句
for (int i = 0; i < tt.Length; i++)
{
if (tt[i] == 1)
{
temp += sqlarry[i];
tt[i] = 0; //標誌位清0;
}
}
//整合出最後的SQL語句
strSql = strSql + temp + strSql2;
...(執行資料庫查詢語句)