存储过程输出参数返回Null

时间:2016-03-11 07:42:59

标签: c# sql-server stored-procedures

我试图从我在数据库中的存储过程返回一个输出参数。但是,我收到一个错误:“对象引用未设置为对象的实例。”,因为我的参数返回为Null。

这是我的代码:

    public IList<UserExperimentHistory> FindPaginated(int pageNumber, int rowsByPage, string orderByType, out int totalCount)
    {
        using (var connection = new SqlConnection(_connectionString))
        {
            var command = new SqlCommand(FindPaginatedSql, connection);
            command.Parameters.AddWithValue("@OrderBy", orderByType);
            command.Parameters.AddWithValue("@RecordFrom", pageNumber * rowsByPage - rowsByPage + 1);
            command.Parameters.AddWithValue("@RecordTo", pageNumber * rowsByPage);


            SqlParameter output = new SqlParameter("@Rows", SqlDbType.Int);
            output.Direction = ParameterDirection.Output;
            command.Parameters.Add(output);

            command.CommandType = CommandType.StoredProcedure;                

            connection.Open();

            using (SqlDataReader reader = command.ExecuteReader())
            {
                totalCount = (int)output.Value;
                var experiments = new List<UserExperimentHistory>();
                while (reader.Read())
                {
                    experiments.Add(ReadUserExperiment(reader));
                }
                return experiments;
            }


            //if (connection.State != ConnectionState.Open) connection.Open();
            //command.ExecuteNonQuery();
            //totalCount = Convert.ToInt32(command.Parameters["@Rows"].Value);

        }
    }

0 个答案:

没有答案