SqlDataReader with no rows.

  • Thread starter Thread starter me
  • Start date Start date
M

me

I am using a sqldatareader with this command:

select max(id) from x

If there is no rows in table x then using
sqldatareader.read() still return true as if
there is a row, which means this code breaks:

if (sqldatareader.read()) {
... = sqldatareader.GetInt32(0); // field 0 is null!?
}

All the examples i have seen on ms website and
in books dont take any precautions for empty
tables. Right now i am doing this:

if (sqldatareader.read() && !sqldatareader.IsDBNull(0)) {
... = sqldatareader.GetInt32(0);
}

It seems clumsy. I am doing somthing wrong here?
 
me said:
I am using a sqldatareader with this command:

select max(id) from x

If there is no rows in table x then using
sqldatareader.read() still return true as if
there is a row, which means this code breaks:

if (sqldatareader.read()) {
... = sqldatareader.GetInt32(0); // field 0 is null!?
}

All the examples i have seen on ms website and
in books dont take any precautions for empty
tables. Right now i am doing this:

if (sqldatareader.read() && !sqldatareader.IsDBNull(0)) {
... = sqldatareader.GetInt32(0);
}

It seems clumsy. I am doing somthing wrong here?

Nope - the result of your select is *exactly* a table with a single
row, which has a null value. If you execute the query in SQL Server
Enterprise Manager you'll see the same behaviour.
 
Hello,

If you're using version 1.1 of the .Net framework, you can use the HasRows
property to test for this.

Hope that helps!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top