I am running a sql query to return the largest value in a column back to the program.
The sql query i run is..
select MAX([Line No]) from table
I am using sql server 2008.
The table has 3 rows, ‘Line No’ has values 50, 90, 100
the max value i expect to be returned is 100,
but im getting 90..why?
EDIT:
string LineNo = "0";
//LineNo
string SQLlineno = "select MAX(CAST([Line No] As Int)) from Saved_Order_Import where [order no] = '"
+ ordernumber + "'";
SqlCommand myCommandlineno = new SqlCommand(SQLlineno, myConnection);
SqlDataReader readerline;
try
{
readerline = myCommandlineno.ExecuteReader();
if (readerline.HasRows)
{
while (readerline.Read())
{
try
{
if (readerline.GetString(0) != null)
{
LineNo = (readerline.GetString(0) + 10).ToString();
}
}
catch (Exception ex) { return "{\"error\":\"line : " + ex.ToString() + "\"}"; }
}
}
readerline.Close();
}
catch (Exception ex)
{
// return "{\"error\":\"Other One11" + ex.ToString() + "\"}";
}
Your column is likely not a numeric type but a string type (char, nchar, varchar, nvarchar). So, it is sorting alphabetically, and 9 comes after 1.
The easiest thing is to change to the correct data type for that column. If you can’t do that, you’ll need to cast back to the correct type inside the
MAX.E.g.,
If you have some values in that column that cannot be converted to a number that you want to filter out, you can do:
Or, to only show the non-numeric values, so you can fix them, you could do:
For more robust integer detection, see this article: Can I Convert This String to an Integer?