Click here to Skip to main content
15,923,051 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have got a SQL database table in which i am querying from in my c# project. The table contains a column that takes in int as a datatype (Employers Age). I am querying from this column and I would like each and every record that is queried from this column to be added up and display the total of the records;

Code:

C#
int AddAge;
string getAge;

    Query = "SELECT * FROM TblEmp WHERE Id = '" + id + "' AND Position = '"+Manager+"'";
                       theReader = conn.ExecuteStatement(Query);
                       while(theReader.Read())
                       getAge = theReader["Age"].ToString();
                       AddAge = int.Parse(getAge);


                     AddAge + getAge;
                      // this is where i am stuck, How can I add up the ages and display the the total?
Posted
Comments
[no name] 31-Mar-14 10:15am    
Look up the SQL SUM function.
PIEBALDconsult 31-Mar-14 19:44pm    
As others have said, use SUM ; then use ExecuteScalar.

Other than that...

For one thing, your code requires braces around the statements that should be in the while loop.
For another, don't use ToString on the returned value when you know it's an integer -- just cast it -- this avoids the Parse.
For yet another, AddAge + getAge; does nothing even if it compiles at all.

Avoid using SELECT * when you don't actually want all the values.
And finally, you should be using a parameterized query.

Let pause and ask yourself a question, how do you find out the age of a person? His date of birth, right. Age is not constant and is derivable from date of birth which is fixed for each individual. You should be storing date of birth, not age in the database table.
To find the age of a person, simply retrieve his date of birth from the table, do the calculation in code behind based on the current date and you will always get the correct age. In this way, you can sum the ages of all persons in code behind and always get the latest update.
 
Share this answer
 
v5
Comments
PIEBALDconsult 31-Mar-14 19:35pm    
Except do it in the database, not in the code.
If this query is used solely for the total age added together than use that in the query. Otherwise use another query to get only the sum

C#
Query = "SELECT SUM(Age) as totalAge FROM TblEmp WHERE Id = '" + id + "' AND Position = '"+Manager+"'";


When in doubt see w3School[+] ;-)
 
Share this answer
 
Comments
PIEBALDconsult 31-Mar-14 19:35pm    
Use a parameterized query.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900