2016-06-01 121 views
2

我需要根據用戶輸入的asp.net Web應用程序中的4列過濾sql數據庫。這種情況下,他們可以選擇或不是全部四列或一列或2等。我擁有的是2^4(16)種可能性。什麼是最好的方法來過濾?篩選數據庫

gui截圖:

screenshot

請指引我。

我寫了四種情況之一的選擇查詢:

SELECT acct_number AS AccountNo, 
    cust_lname AS Name 
FROM List 
WHERE (ordr_date='" + orderdate + "' 
    OR reader_code='" + rdrCode + "' 
    OR dly_pack_no='" + dlyPack + "' 
    OR walk_seq='" + wlkSeq + "') 
+1

您能否請您顯示您當前的查詢? – navnit

+2

Yieks!請使用參數化查詢,因爲這很容易發生SQL注入。 – Adwaenyth

+0

參數化查詢! – Takarii

回答

3
SELECT acct_number AS AccountNo, 
     cust_lname AS Name 
FROM List 
WHERE (ISNULL(orderdate,'')='' OR ISNULL(ordr_date,'')='' OR ordr_date='" + orderdate + "') 
    AND (ISNULL(rdrCode,'')='' OR ISNULL(reader_code,'')='' OR reader_code='" + rdrCode + "') 
    AND (ISNULL(dlyPack,'')='' OR ISNULL(dly_pack_no,'')='' OR dly_pack_no='" + dlyPack + "') 
    AND (ISNULL(wlkSeq,'')='' OR ISNULL(walk_seq,'')='' OR walk_seq='" + wlkSeq + "') 
+0

Thx,它工作正常! – Kayathiri

0

試試下面的查詢。

SELECT acct_number AS AccountNo , 
    cust_lname AS Name 
FROM List 
WHERE (ordr_date = '" + orderdate + "' 
     OR " + orderdate + " = " + orderdate + " 
    ) 
    AND (reader_code = '" + rdrCode + "' 
      OR " + rdrCode + " = " + rdrCode + " 
     ) 
    AND (dly_pack_no = '" + dlyPack + "' 
      OR " + dlyPack + " = " + dlyPack + " 
     ) 
    AND (walk_seq = '" + wlkSeq + "' 
      OR " + wlkSeq + " = " + wlkSeq + " 
     ) 
+0

不..它不排序。總是給出相同的結果。 – Kayathiri

+1

嘗試使用下面給出的Moumit答案給我的答案。這是比較適合我的答案。 – navnit

0

建立你的WHERE動態-clause和使用參數。

SqlCommand select = new SqlCommand(@"SELECT acct_number AS AccountNo, 
    cust_lname AS Name 
    FROM List "); 

if(!string.IsNullOrWhiteSpace(orderDate)) // use appropriate logic according to data type. I'm assuming string atm. 
select.Parameters.Add(new SqlParameter() { ParameterName = "@ordr_date", Value = orderDate, SqlDbType = SqlDbType.NVarChar }); 

// Repeat for each parameter and then... 

for(int i = 0; i < select.Parameters.Count; i++) 
{ 
    if(i == 0) 
     select.CommandText += " WHERE "; 
    else 
     // OR as in the filter is not exclusive... depends on the filter logic you want to construct of course. 
     // AND if it has to fulfill all properties 
     select.CommandText += " OR "; 
    select.CommandText += string.Format("{0} = {0}", select.Parameters[i].Name).Substring(1); 
} 
+0

爲什麼「OR」?爲什麼'{1}'? – Serg

+0

Thx,'{0}'當然是兩倍......'OR'就像過濾器不是唯一的......取決於你想要構造的過濾器邏輯。如果它必須滿足所有屬性,則爲'AND'... – Adwaenyth