Author Topic: The difference between GetSqlValue and GetValue  (Read 11865 times)

Offline admin

  • Administrator
  • Sr. Member
  • *****
  • Posts: 296
    • View Profile
The difference between GetSqlValue and GetValue
« on: January 25, 2009, 02:18:43 PM »
 The GetValue method is also slightly faster than the Item accessors. The Item property simply calls into GetValue and in so doing transforms the column name into an index. The difference between GetSqlValue and GetValue is all in the type they return. The former returns a .NET type that mimics a native SQL Server type; the latter returns the content of a field as an instance of a base .NET type. The data reader features a handful of type-specific methods, such as GetString, GetDateTime, GetSqlString, and GetSqlDateTime. The GetXXX methods just call into the corresponding GetSqlXXX and then extract the actual value from the SQL wrapper type. The SQL types are just wrappers around a .NET object, as the following pseudo-code demonstrates.

Code: [Select]
string GetString(int i) {
   SqlString str = GetSqlString(i);
   return str.Value;
}
GetSqlXXX methods are slightly faster than corresponding GetXXX methods. The reason for the better performance lies in the fact that the data types in the .NET Framework SqlDbType enumeration closely match the internal representation of types made by SQL Server. As a result, no conversion is required to return data to the application.

The performance improvement provided by GetSqlXXX methods is not dramatic, but there are other reasons to consider their use. Using SQL types allows for a more comfortable and lazier manipulation of null values. For example, if you attempt to store a null value contained in one of the columns retrieved in a .NET type, at a minimum you get an exception. By contrast, nothing bad happens if you store a null value in a SQL type. The IsNull method on each SQL type lets you check for the null value later. The IsDBNull method on the data reader class lets you check whether the data is storing null when GetXXX methods are used, but you have to check it right after you retrieve the data to avoid exceptions.

Another reason for using SQL types is that in this way you may avoid loss of precision during the conversion. For example, the decimal type has 38 digits in SQL Server, but only 28 in the .NET type system.