it does not gave any value
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Paied) FROM Debt", new SqlConnection(Program.ConnectionString)))
{
cmd.Connection.Open();
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
TotalPaiedAll = Convert.ToDecimal( myRea开发者_StackOverflowder["Paied"].ToString());
}
cmd.Connection.Close();
}
Your SQL query should be
SELECT SUM(Paied) AS Paied FROM Debt
Alternatively, you could use
SELECT SUM(Paied) AS Paied FROM Debt TotalPaiedAll = (decimal) cmd.ExecuteScalar();
The reason you're not getting a value is because SUM(Paied)
generates an anonymous column, not a column named Paied.
Here is a simple fix for your problem:
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Paied) As SumOfPaid FROM Debt", new SqlConnection(Program.ConnectionString)))
{
cmd.Connection.Open();
SqlDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
TotalPaiedAll = Convert.ToDecimal(myReader["SumOfPaid"].ToString());
}
cmd.Connection.Close();
}
And here is a better approach, using the ExecuteScalar method:
using (SqlCommand cmd = new SqlCommand("SELECT SUM(Paied) As SumOfPaid FROM Debt", new SqlConnection(Program.ConnectionString)))
{
cmd.Connection.Open();
TotalPaiedAll = (decimal)cmd.ExecuteScalar();
cmd.Connection.Close();
}
use executescalar instead of executereader:
decimal sum =(decimal) cmd.ExecuteScalar();
there is no point in doing a while loop because the sum is just a single value.
Not your bug but you also need to protect the sql connection against leakage.
精彩评论