PDA

Click to See Complete Forum and Search --> : Help with my query string


daimous
Sep 17th, 2006, 09:34 PM
hi guys! i have a code below that query something from my database

string SqlConnStr = Properties.Settings.Default.MyConnString;
sqlConn = new SqlConnection(SqlConnStr);
sqlConn.Open();
string qryStr = "Select Max(number) from docs_ref";
SqlCommand SqlCmd = new SqlCommand(qryStr, sqlConn);
object result = SqlCmd.ExecuteScalar();
SqlCmd.Connection.Close();
sqlConn.Close();

but how can I check if it does return any value or not and if it does how can i retrieve the value? thanks.

jmcilhinney
Sep 17th, 2006, 10:51 PM
object result = SqlCmd.ExecuteScalar();The 'result' variable contains the value returned by the query. I'm not 100% sure but I would guess that if the 'number' column contains no values then 'result' would contain DBNull.Value. I am sure that if the 'number' column does contain values then 'result' will contain the largest of them and its type will correspond to the type of the column. If the column contains integers:object result = SqlCmd.ExecuteScalar();

if (result is int)
{
// Cast the result as an integer.
int maxNumber = (int)result;

// Use maxNumber here.
}