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.

Recommended Answers

All 6 Replies

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];
                        }
                    }
                }
            }

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

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!

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

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.