簡單的條件查詢演算法

來源:互聯網
上載者:User

剛剛學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;
        ...(執行資料庫查詢語句)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.