3

I'am posting on this forum for the first time . and I really hope I can find some help . What I'am doing is load about ... 1000 Value (example) from SQL and I'am doing it just fine .

the query for example is : Select Value from DatabaseA.dbo.Values

that "Value" ==> decimal(10, 2)

sqlConnection2.Open();
insertCommand2.ExecuteNonQuery();
SqlDataReader reader2 = insertCommand2.ExecuteReader();
if (reader2.HasRows)
{
  while (reader2.Read())
  {
    decimal Value = reader.GetDecimal(0);

this propably should work fine . but What I want to do is to make + on all of them ... For example first value = 16 , second = 28 , third : 78

I want to make 16 + 28 + 78 ... but for all Values that Loaded them . How Can I do that please ? , thanks .

2
  • 1
    The code makes no sense. You show us a SELECT query but you're using ExecuteNonQuery, then you're using ExecuteReader on the same command to get a SqlDataReader reader2 but you're using reader later which you haven't shown at all. Commented Sep 13, 2013 at 9:42
  • Are you saying you want a total sum or a running total? Ie if the rows are 10/12/10 would you like just 32 or 10/22/32? Commented Sep 13, 2013 at 9:44

4 Answers 4

3

Assuming you want to keep the original values as well, you could have a List<decimal> and accumulate the totals.

List<decimal> totals = new List<decimal>();

Then in your while loop:

totals.Add(Value);

You can then return the running total via:

var runningTotal = totals.Sum();

If you do not want the original values, you can just use:

 decimal value;
 while (reader2.Read())
 {
    value += reader.GetDecimal(0);
 }
Sign up to request clarification or add additional context in comments.

Comments

2

Just take your variable outside of your loop and use the += operator

decimal Value = 0;
sqlConnection2.Open();
insertCommand2.ExecuteNonQuery();
SqlDataReader reader2 = insertCommand2.ExecuteReader();

if (reader2.HasRows)
{
    while (reader2.Read())
    {
       Value += reader.GetDecimal(0);
    }
}

Comments

1

change sql as

Select Sum(Value) from DatabaseA.dbo.Values

and then

decimal Value = (decimal)insertCommand2.ExecuteScalar(); 

Comments

0

You could use the SQL SUM function. Take a look at http://technet.microsoft.com/en-us/library/ms187810.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.