What\'s the difference between reading a value from an SqlDataReader using this syntax:
Dim reader As SqlClient.SqlDataReader
reader(\"value\").ToString()
I just want to add that the context of how many records you are expecting plays a big role because if you are returning a single row then performance difference between those two would not be significant. However if you are looping over many rows then using typed accessor is better for performance since it's optimized. So in that case if you need to get best performance by using a column name then call GetOrdinal once, put it into a variable and then use typed accessor with the column ordinal in your loop. This would yield the best performance.
if you are curious about the performance difference check out my blog post
Your mileage may vary, but...
The more rows you are fetching, the more of a performance improvement you will see. I like to use column aliases in my SELECT statements, like
select
physical_column_name as "MyFieldName"
and have written a method, should be self-explanatory,
public Dictionary<String, Int32> GetOrdinalsByName(DbDataReader reader)
So, then my assignments look like
public void BindRow(DbDataReader dr)
{
TerminationDate = dr.GetDateTime(_columnOrdinals["TerminationDate"]);
Dictionaries execute close to O(1); so, this is a reasonable tradeoff between performance and maintainability.
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.
Source: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getordinal.aspx
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);
}