3
Contributors
6
Replies
7
Views
6 Years
Discussion Span
Last Post by Momerath
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];
                        }
                    }
                }
            }
0

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

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!

Edited by Mitja Bonca: n/a

0

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

0

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

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.

Edited by Momerath: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.