vb.net 使用 Where 子句过滤 SqlDataReader

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24251752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:42:50  来源:igfitidea点击:

Filter SqlDataReader with Where Clause

c#.netvb.netado.netsqldatareader

提问by Software Enginner

I have the Client as below

我有如下客户

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

My requirement to retrieve the results and filter them, through SqlDataReaderonly.

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

Here what I'm doing,

这是我在做什么,

I'm executing the select statement from SqlDataReader.
Once the results are returned to my SqlDataReader, then I'm not able retrieve the results by keeping where clause on SqlDataReader.

我正在从SqlDataReader.
一旦结果返回到 my SqlDataReader,我就无法通过将 where 子句保留在 上来检索结果SqlDataReader

May I know, how can I read the SqlDataReaderwith condition based?

我可以知道,我如何阅读SqlDataReader基于条件的内容?

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'                
    }
}

Please suggest??

请推荐??

回答by Steve

A normal SQL WHERE clause is the right path for this. It will retrieve only the records required and no more testing with if are necessary to filter out the unwanted rows. Of course, a parameterized query will help a lot with the possibile variance of the filter

一个普通的 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"
    }
}

Other advantages of this approach are explained in the comment above from Mr Joel Coehoorn.

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

回答by paparazzo

Reader cannot filter until it reads but you can continue.

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

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