Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I call SqlDataReader.HasRows if I am calling SqlReader.Read

Tags:

Trying to see if it is beneficial to add an if (dr.HasRows) before the while (dr.read()) function. I mean, technically if it doesn't have rows it isn't going to read, so would it matter if you checked this first?

using (SqlDataReader dr = cmd.ExecuteReader())
{
    if (dr.HasRows)
    {
        while (dr.Read())
        {
            ....do stuff here
        }
    }
}

or is this going to essentially do the exact same thing if you're just making sure it has values to provide...

using (SqlDataReader dr = cmd.ExecuteReader())
{
    while (dr.Read())
    {
        ....do stuff here
    }
}    
like image 494
Joshua Volearix Avatar asked Jan 07 '13 13:01

Joshua Volearix


4 Answers

No..It is not mandatory to check (dr.HasRows) if the DataReader contains any row or not.

Read() will return False if there are no more rows to fetch, but Reader.HasRows is much more telling as to what it does than Read() so it would be a good practice to use Reader.HasRows because you may accidentally do something other than Read() which may fall into exception.

like image 67
Vishal Suthar Avatar answered Nov 03 '22 21:11

Vishal Suthar


Be careful. HasRows() returns false for my CTE query, even though there are rows (437 rows actually).

like image 41
Chalky Avatar answered Nov 03 '22 21:11

Chalky


It's not mandatory to check if the DataReader has rows (dr.HasRows). The Read() method will return true if there is more data to read and false if there's no more data, thus breaking the while-loop.

like image 45
Abbas Avatar answered Nov 03 '22 23:11

Abbas


I think this is mostly for stored procedures which may or may not have data (one or more result sets) and it is "easier" to check first in case you also do other stuff than the while loop (i.e. initialize header/footer etc. when there is data).

like image 44
TomTom Avatar answered Nov 03 '22 23:11

TomTom