如何通过c#在SQL中检索SUM函数的值

时间:2015-04-10 07:58:31

标签: c# mysql sql-server stored-procedures

我有一个存储过程CalculateTotal,用于从表支出中返回Amount列中所有记录的SUM

`CREATE PROCEDURE CalculateTotal
 @Name varchar(50),
 @Month int
 @year
 As
 SELECT SUM(Amount) As Total
 FROM Spendings
 WHERE MONTH(Date) = @Month AND YEAR(Date)= @Year AND Name = @Name`

当我从SQLServer执行此过程时,执行成功并返回总金额,
我需要从C#中获取Total的值,我尝试了以下代码,

public void CalculateTotal(string name, int month , int year)
 {
     cmd = connection.CreateCommand();
     cmd.CommandText = "EXECUTE CalculateTotal @Name,@Month,@Year";
     cmd.Parameters.AddWithValue("@Name", name);
     cmd.Parameters.AddWithValue("@Month", month);
     cmd.Parameters.AddWithValue("@Year", year);
     reader = cmd.ExecuteReader();          
     if(reader.HasRows)
     {
           while (reader.Read())
           {
               int total = (int)reader["Total"];
           }
      }
}

当我调试它时,'while'条件为真,当'while'循环体执行时遇到一个名为IndexOutOfRangeException的错误:总计

如何在c#

中检索SUM函数的值

4 个答案:

答案 0 :(得分:1)

通过ADO从SQL Server返回单个值时,我建议您使用ExecuteScalar。用法示例:

    Int32 total= (Int32)cmd.ExecuteScalar();

另请参阅实现使用模式以确保不会导致内存泄漏。

答案 1 :(得分:1)

可以尝试这样的事情。

public void CalculateTotal(string name, int month , int year)
 {
     cmd = connection.CreateCommand();
     cmd.CommandText = "CalculateTotal";
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.AddWithValue("@Name", name);
     cmd.Parameters.AddWithValue("@Month", month);
     cmd.Parameters.AddWithValue("@Year", year);
     connection.Open();
     string result = cmd.ExecuteScalar().ToString();
     connection.Close();
}

答案 2 :(得分:0)

更改您的程序;

 CREATE PROCEDURE CalculateTotal
 @Name varchar(50),
 @Month int
 @year int
 @Total int Output
 As
 BEGIN
 SELECT @Total = SUM(Amount)
 FROM Spendings
 WHERE MONTH(Date) = @Month AND YEAR(Date)= @Year AND Name = @Name
 END

您需要将return参数添加到命令:

public void CalculateTotal(string name, int month , int year)
 {
     cmd = connection.CreateCommand();
     cmd.CommandText = "CalculateTotal";
     cmd.CommandType = CommandType.StoredProcedure;
     cmd.Parameters.AddWithValue("@Name", name);
     cmd.Parameters.AddWithValue("@Month", month);
     cmd.Parameters.AddWithValue("@Year", year);
     var returnParameter = cmd.Parameters.Add("@Total", SqlDbType.Int);
     returnParameter.Direction = ParameterDirection.ReturnValue;
     int total = (Int32)cmd.ExecuteScalar(); 
}

答案 3 :(得分:0)

我尝试使用下面显示的示例代码:

SqlCommand cmd2 = new SqlCommand();
cmd2 = con.CreateCommand();
cmd2.CommandText = "gettotalprice";
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.Parameters.AddWithValue("@ordernums", ordnum.Text);
string result = cmd2.ExecuteScalar().ToString();
Label2.Text = "<b>Total Amount= </b>" + result + " Rs.";

对我来说这很好,没有任何问题,我得到了总金额。