簡體   English   中英

使用Where子句過濾SqlDataReader

[英]Filter SqlDataReader with Where Clause

我有以下客戶

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

我要求檢索結果並僅通過SqlDataReader對其進行過濾。

這是我在做什么

我正在執行SqlDataReader的select語句。
一旦結果返回到我的SqlDataReader ,那么我將無法通過在SqlDataReader上保留where子句來檢索結果。

我可以知道,如何基於條件讀取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'                
    }
}

請提出建議?

普通的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先生在上面的評論中解釋了這種方法的其他優點。

閱讀器無法過濾,直到讀取為止,但您可以繼續。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM