Nyprez Nyprez - 6 months ago 15
SQL Question

Read MAX value from db and avoid null, using ExecuteScalar

How do I avoid null and instead get integer 0?

cmd.CommandText = "SELECT MAX(*) " +
"FROM [Test] " +
"WHERE ID = @id ;";

cmd.Parameters.AddWithValue("@id", ID);
cmd.ExecuteNonQuery();
Amount = (int)cmd.ExecuteScalar();

Answer

first you must specify column which you want calcul MAX SELECT MAX(column_name) and you can use this :

object obj = cmd.ExecuteScalar();

Amount = (obj != null && obj != DBNull.Value) ? Convert.ToInt32(obj) : 0 ;