954,510 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

determining largest number and storing in variable

please tell me c# code i want to determine largest number in a column of sql server 2000 table and store it in a variable.

arsalanghouri
Newbie Poster
13 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 
int myVariable = 0;
            using (SqlConnection sqlConn = new SqlConnection("connString"))
            {
                using (SqlCommand cmd = new SqlCommand(@"SELECT MAX(MyColumnName) FROM MyTable", sqlConn))
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            if (reader.GetValue(0) != DBNull.Value)
                                myVariable = (int)reader[0];
                        }
                    }
                }
            }
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
 

code not working not giving the required result and showing exception in try catch

arsalanghouri
Newbie Poster
13 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

I hope you didnt use the exact code I pasted?!
You have to change the Sql query (to suit your dataBase design) and you have to use your connection string while creating a new reference of SqlConnection class.

And one more thing: I boxes the retreived value to integer. Is the column type of integer? If not, change to the right one.

If this is not it, please tell me what the error is!

Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
 

i know the query for determining the maximum number but how to execute it? using data reader or execute scalar and then how to save the result in a variable

arsalanghouri
Newbie Poster
13 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

yes of course i modified the code
column is numeric type
and i am posting the error

arsalanghouri
Newbie Poster
13 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

Change lines 6-13 to read:

decimal maxValue = (decimal)cmd.ExecuteScaler();

Yep, just the one line. This is for numeric data, if another type, change the (decimal) to whatever type it is.

Momerath
Nearly a Senior Poster
3,384 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: