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
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
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