2012-02-24 98 views
1

我不確定這是否可能,但只是需要解決當前問題。 我有一個數據層的方法,它返回SqlDataReader對象。這稍後由業務層調用。在不關閉數據讀取器的情況下讀取輸出參數

public SqlDataReader GetAll(out int count) 
{ 
    using (SqlConnection conn = new SqlConnection()) 
{ 
    IDataReader reader = null; 
    SqlCommand cmd = new SqlCommand("sproc", conn); 
    cmd.CommandType = CommandType.StoredProcedure; 

    // add parameters 
    SqlParameter outputParam = cmd.Parameters.Add("@Count", SqlDbType.Int); 
    outputParam.Direction = ParameterDirection.Output; 

    conn.Open(); 

    reader = cmd.ExecuteReader(); 
    { 
     while(reader.Read()) 
     { 
      //read in data 
     } 
     **// not possible as the reader is not closed. 
     // need to set this out variable here 
     count = outputParam.Value; //doesn't work/** 

    } 

} 
return reader; 
} 

如果問題不清楚,請讓我知道。

+0

是代碼你有嗎?您已經完成了讀取結果(除非您有存儲過程返回的多個結果集),爲什麼不關閉讀取器並獲取OUT參數值呢? – alwayslearning 2012-02-25 00:21:50

回答

0

請看看這段代碼:

using(SqlConnection connection = new SqlConnection(connectionString)) 
     { 
      connection.Open(); 

      SqlCommand command = new SqlCommand("testproc", connection); 
      command.CommandType = CommandType.StoredProcedure; 

      var countParam = command.CreateParameter(); 
      countParam.ParameterName = "@TotalCount"; 
      countParam.Direction = ParameterDirection.Output; 
      countParam.DbType = DbType.Int32; 
      command.Parameters.Add(countParam); 


      using (IDataReader reader = command.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        Console.Write("exec"); 
       } 

       totalCount = (int)countParam.Value; //totalCount has valid value 
      } 
     } 
+0

我知道我的代碼並不擅長設計本身。但這就是我必須努力的。 @SergeyG:我認爲我們的代碼幾乎是相似的。對你起作用嗎? – PraveenLearnsEveryday 2012-07-31 11:50:53

相關問題