过滤数据库

时间:2016-06-01 11:40:53

标签: c# sql asp.net

我需要根据sql Web应用程序中4列的用户输入过滤asp.net数据库。这种情况,他们可以选择或不选择所有四列或一列或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 + "')

3 个答案:

答案 0 :(得分: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 + "')

答案 1 :(得分: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 + "
        )

答案 2 :(得分:0)

动态构建WHERE - 子句并使用参数。

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);
 }