Possible to return an out parameter with a DataReader

后端 未结 2 830
自闭症患者
自闭症患者 2021-01-17 12:24

Using ExecuteReader I am able to return a DataReader, but the out parameter is returning 0.

Using ExecuteNonQuery I am able to retrieve the

相关标签:
2条回答
  • 2021-01-17 13:05

    The value for your output parameter is in the stream from SQLServer AFTER any results sets returned (I believe this is also true of the return value). That means you won't see the value until after you read all the rows from the DataReader (or close it I believe). So an output parameter that tells you the number of rows in the result set is of little use.

    However, the code fragment below demonstrates the sequence of operations you should be using:

    using(SqlConnection connection = new SqlConnection("[your connection string here]"))
    {
      connection.Open();
    
      using (SqlCommand command = connection.CreateCommand())
      {
        command.CommandType = CommandType.StoredProcedure;
        command.CommandText = "dbo.SelectDays";
    
        command.Parameters.AddWithValue("@dateStart", dateStart != null ? (object)dateStart : DBNull.Value);
        command.Parameters.AddWithValue("@dateEnd", dateEnd != null ? (object)dateEnd : DBNull.Value);
    
        SqlParameter out_recordCount = new SqlParameter("@recordCount", SqlDbType.BigInt);
        out_recordCount.Direction = ParameterDirection.InputOutput;
        out_recordCount.Value = recordCount;
    
        command.Parameters.Add(out_recordCount);
    
        SqlParameter return_Value = new SqlParameter("@RETURN_VALUE", SqlDbType.Int);
        return_Value.Direction = ParameterDirection.ReturnValue;
        command.Parameters.Add(return_Value);
    
        using(SqlDataReader reader = command.ExecuteReader())
        {
          while(reader.Read()) { /* do whatever with result set data here */ }
        }
    
        /* Output and return values are not available until here */
    
        if (out_recordCount.Value != DBNull.Value)
          recordCount = Convert.ToInt64(out_recordCount.Value);
    
        returnValue = Convert.ToInt32(return_Value.Value);
    
        return returnValue;
      }
    }
    
    0 讨论(0)
  • 2021-01-17 13:10

    To get the values from OUTPUT parameters with SqlDataReader you can only after the reader will be closed.

    So you need to add this code before you try to get the values

    if(!dataReader.IsClosed)
        dataReader.Close(); 
     if(out_recordCount.Value != DBNull.Value)
         recordCount = Convert.ToInt64(out_recordCount.Value);
     returnValue = Convert.ToInt32(return_Value.Value);
    
    0 讨论(0)
提交回复
热议问题