2013-04-25 50 views
0

我有我用來處理來自兩個表的數據的以下代碼,但我似乎無法讓兩個SqlDataReaders使用它。任何想法如何改變它使其工作?在ASP.NET中使用兩個SqlDataReaders

//SqlConnection cn = valid SQL Server 2008 connection 

using (SqlCommand cmd = new SqlCommand("SELECT * FROM table1", cn)) 
{ 
    using (SqlDataReader rdr = cmd.ExecuteReader()) 
    { 
     while (rdr.Read()) 
     { 
      int nVal1 = rdr.GetInt32(0); 
      int nVal2 = rdr.GetInt32(1); 
      //... 
      int nValN = rdr.GetInt32(N); 

      //Now I process the data read ... 

      //After processing I need to use the results 
      //to look up data from another table using 
      //this item's data 

      using (SqlCommand cmd2 = new SqlCommand("SELECT * FROM table2 WHERE " + strSQLCondition, cn)) 
      { 
       //But code below doesn't let me create another reader 
       using (SqlDataReader rdr2 = cmd2.ExecuteReader()) 
       { 
        while (rdr2.Read()) 
        { 
         //Process results 
        } 
       } 
      } 

     } 
    } 
} 

回答

3

默認情況下,您只能在連接上使用一個活動數據集。你有幾個選擇。浮現在腦海中的三個都是

  1. 手之前查找的數據,並將它緩存
  2. 使用第二個連接對象的內部命令
  3. 使用MARS - http://msdn.microsoft.com/en-us/library/ms131686.aspx
+0

感謝。打開另一個連接有助於我不知道爲什麼我自己沒有想到:) – ahmd0 2013-04-25 17:14:06

相關問題