【问题标题】:Filter SqlDataReader with Where Clause使用 Where 子句过滤 SqlDataReader
【发布时间】:2014-06-16 20:32:25
【问题描述】:

我有如下客户端

Id  Name status  
1   A      Y  
2   B      Y  
3   C      Y  
4   D      N  

我要求仅通过SqlDataReader 检索结果并过滤它们。

这是我正在做的,

我正在执行来自 SqlDataReader 的 select 语句。
一旦结果返回到我的SqlDataReader,我就无法通过在SqlDataReader 上保留 where 子句来检索结果。

请问,我怎样才能阅读SqlDataReaderwith condition based?

SqlCommand command = new SqlCommand("SELECT ID, Name , Status FROM Client;",connection);
connection.Open();

SqlDataReader reader = command.ExecuteReader();

if (reader.HasRows)
{
    while (reader.Read())
    {
        //Here, I have to to filter the results like
        //Select * from Client where status = 'N'                
    }
}

请推荐??

【问题讨论】:

  • 请问为什么普通的 SQL WHERE 子句在这里不好?
  • 这似乎是一个非常糟糕的主意。它迫使你的客户做过滤工作,而不是让数据库去做。数据库在这方面擅长:它具有索引和其他功能,可以有效地过滤数据。通过网络将整个表拉到客户端也很慢。
  • @JoelCoehoorn,我理解您的担忧。但是,在进入业务场景的下一步之前,我必须从 .Net 端进行过滤,因为我必须看到整个结果。

标签: c# .net vb.net ado.net sqldatareader


【解决方案1】:

一个普通的 SQL WHERE 子句是正确的路径。它将仅检索所需的记录,并且不再进行测试以过滤掉不需要的行。当然,参数化查询对过滤器的可能方差有很大帮助

SqlCommand command = new SqlCommand(@"SELECT ID, Name , Status FROM Client
                                      WHERE status = @st;",connection);    
command.Parameters.AddWithValue("@st", "N");  // Or use a passed string variable
connection.Open();
SqlDataReader reader = command.ExecuteReader();

if (reader.HasRows)
{
    while (reader.Read())
    {
        // Here you have only the records with status = "N"
    }
}

Joel Coehoorn 先生在上面的评论中解释了这种方法的其他优点。

【讨论】:

  • 陈述的问题是“我要求仅通过 SqlDataReader 检索结果并过滤它们。”这没有解决所述问题。如果您觉得问题有误,那么补救措施就是发表评论。
  • 也许您对“陈述的问题”是正确的,但这不应该阻止任何人通过答案展示处理这种情况的正确方法。我觉得在这里只发表评论是不够的。就像说:“你做错了......”然后走开,让海报在黑暗中。另一方面,如果答案的缺点多于优点,那么您给出“对所述问题的正确”答案也是正确的。 (顺便问一下,你能解释一下用SqlDataReader过滤是什么意思吗?)
【解决方案2】:

阅读器在读取之前无法过滤,但您可以继续。

while (reader.Read())
{
    status = rdr.getstring(1);
    if (status != 'N') continue;
    // process 
}

【讨论】:

    猜你喜欢
    • 2021-08-01
    • 1970-01-01
    • 2012-06-20
    • 2015-04-10
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    相关资源
    最近更新 更多