views:

541

answers:

2

What's the difference between reading a value from an SqlDataReader using this syntax:

Dim reader As SqlClient.SqlDataReader
reader("value").ToString()

OR

Dim reader As SqlClient.SqlDataReader
reader.GetString(reader.GetOrdinal("value"))
A: 

I think that the reason to use GetOrdinal() is so that you can cache the result and re-use it multiple times for performance.

E.g.

Dim reader As SqlClient.SqlDataReader
int valueOrdinal = reader.GetOrdinal("value");
while ( ... )
{
    var value = reader.GetString(valueOrdinal);
}
Alex Black
A: 

GetOrdinal performs a case-sensitive lookup first. If it fails, a second case-insensitive search is made.GetOrdinal is kana-width insensitive.Because ordinal-based lookups are more efficient than named lookups, it is inefficient to call GetOrdinal within a loop. Save time by calling GetOrdinal once and assigning the results to an integer variable for use within the loop.

joe
Word for word copy and pasted from http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal.aspx ;-)
jpoh
@jpoh, nothing wrong with that, usually.
Malfist
Well, at least attribute it.
jpoh
Why not just link to the whole article? His comment is missing lots of content.
Dave