Retrieve MAX value from an SQL column

2
    string var = "";
    SqlConnection con = new SqlConnection(Banco._strCon);
    string sql = "select max(end_id) from endereco";
    SqlCommand cmd = new SqlCommand(sql, con);
    con.Open();
    SqlDataReader dr = cmd.ExecuteReader();

    if (dr.Read())
        var = (dr["max"]).ToString();

    dr.Close();
    con.Close();
    return var;

I need this value of max , but I do not know what to spend within [""] . If I leave like this, the following error appears:

  

dr ["max"] 'dr ["max"]' threw an exception of type 'System.IndexOutOfRangeException' object {System.IndexOutOfRangeException}

    
asked by anonymous 27.10.2015 / 16:26

3 answers

5

Use ExecuteScalar() . Something like this:

string sql = "select max(end_id) from endereco";
SqlCommand cmd = new SqlCommand(sql, con);
con.Open();
return ((int)cmd.ExecuteScalar()).ToString();

The ExecuteReader() should be used to query the data as a whole, when the query will only generate a single data, the correct one is ExecuteScalar() .

    
27.10.2015 / 16:31
3

In your case, you do not need to search by index String :

    if (dr.Read())
        var = (((IDataRecord)dr)[0]).ToString();
    
27.10.2015 / 16:43
3

If you do not know what to put inside the [""], just select the field whose sql function uses the field name. Example:

...
string sql = "select max(end_id) max from endereco";
...
if (dr.Read())
   var = (dr["max"]).ToString();
...

But the best option to implement in this case is bigown

    
27.10.2015 / 17:10