0

This question doesn't really answer a question of mine I've been pondering about for a while even if it's close. What's the difference between

While reader.Read()
End While

and

If reader.HasRows Then
End If

and under which circumstances should either of them be applied? Am I wrong when I assume they both execute if there are any records found in the datareader?

Community
  • 1
  • 1
Kristofer Gisslén
  • 1,252
  • 1
  • 11
  • 28

3 Answers3

1

The code in the While...End While block will be executed for each row in Reader, while the code in the If...End If block will be executed atmost only once, irrespective of how many rows the reader might have.

So when you want to repeat some action for each row in the reader you would use the While Reader.Read() statement.

The If Reader.HasRows Then... is typically used when your reader returns only one rows or no rows, and you want to perform some action based on that.

e.g.

If Reader.HasRows Then
    MessageBox.Show("Record Found!")
Else
    MessageBox.Show("The record was not Found!")
End If
Pradeep Kumar
  • 6,836
  • 4
  • 21
  • 47
0

While reader.Read() End While

While loop Read the each line and executed.

If reader.HasRows Then End If

If reader has rows then only the block of codes work.

While loop used read all lines. but if condition used to only check if the reader has rows or not. if has row then do some work else do some other work.

Sathish
  • 4,419
  • 4
  • 30
  • 59
  • Okay, so what your saying is that a prerequisite to use the while-loop is that I _know_ there's stuff inside the datareader? If I ever doubt there are information inside the datareader I should stick to the if-statement? Are there any other reasons to divide these executions from each other? – Kristofer Gisslén Aug 19 '14 at 11:49
0

Simply put, yes, you are wrong in your assumption.

As you might expect, the While code block will execute once for every row in the returned result set - the Read() instruction returns false when no rows remain in the result set.

However, the If code block will execute exactly once, and only if there are rows in the result set.

In most cases, the While loop will be the one you want to use - even if there are no rows returned from the query, as the Read() call will return false and the entire code block will be skipped.

Psychemaster
  • 876
  • 10
  • 20
  • So, is it reasonable to say that the while-loop uses less resources as it skips the blocks not necessary to execute if there's no records found? :) – Kristofer Gisslén Aug 19 '14 at 12:41
  • 1
    It will in the case that there are no records. However, because the ```If``` block will only execute once regardless of result count, that will conserve resources - but it also won't give the result you may be expecting since it doesn't traverse the data set. – Psychemaster Aug 19 '14 at 12:42