I can not receive the value of a SELECT query

0

I need to extract a single value from the database to assign it to a variable int and then use it, but I can not get it.

Try the syntax of the query and return the value I need, the problem is that I can not assign it, I return the following error on line 5:

System.InvalidOperationException: 'Error de lectura porque no hay datos.'
con.Open();
string str = "SELECT TOP 1 Id FROM productosencola ORDER BY Id DESC;";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader rdr = cmd.ExecuteReader();
int idmax = int.Parse(rdr.GetValue(0).ToString());
    
asked by Medina Nualart Martin 15.05.2017 в 07:23
source

3 answers

1

The problem is that you need to read that datareader. To do this you should first check if there is a row and if you have you can go through them with the .Read() method, after this you can get the value with GetValue() I leave an example:

con.Open();
string str = "SELECT TOP 1 Id FROM productosencola ORDER BY Id DESC;";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader rdr = cmd.ExecuteReader();
int idmax = -1;

if (rdr.HasRows)
{
    while (rdr.Read())
    {
      idmax = int.Parse(rdr.GetValue(0).ToString())
    }
}
    
answered by 15.05.2017 / 09:22
source
0

I use this syntax

int value = rdr ["Id"] == DBNull.Value? 0: (int) rdr ["Id"];

What is enclosed in double quotes is the name of the column or the "nickname" that you oppose in the SELECT by the reserved word AS

In this way, if it is NULL, the value in the DB returns 0 and if it does not save in value what the SELECT has brought as Id.

Greetings

    
answered by 15.05.2017 в 09:20
0

You can declare the variable in the following way:

select @EmpID = ID from productosencola

Attachment most complete answer in English so you can see if this does not work for you.

    
answered by 15.05.2017 в 09:13