Utility function to convert Type to SqlDbType
![]()
Ever needed to convert a System.Type to its corresponding System.Data.SqlDbTye? Here is a nice little utility function that helps you convert a System.Type to it’s corresponding System.Data.SqlDbType.
1: private SqlDbType GetDBType(System.Type theType)2: {3: SqlParameter param;4: System.ComponentModel.TypeConverter tc;5: param = new SqlParameter();6: tc = System.ComponentModel.TypeDescriptor.GetConverter(param.DbType);7: if (tc.CanConvertFrom(theType))8: {9: param.DbType = (DbType)tc.ConvertFrom(theType.Name);10: }11: else12: {13: // try to forcefully convert14: try15: {16: param.DbType = (DbType)tc.ConvertFrom(theType.Name);17: }18: catch(Exception e)19: {20: // ignore the exception21: }22: }23: return param.SqlDbType;24: }



October 21st, 2008 at 8:53 pm
Thank you for the code. This really saved my day.
August 21st, 2009 at 6:34 am
Hi,
Just wanted to point out that this function should not be used with CLR, as the System.ComponentModel.TypeDescriptor is marked with the HostProtectionAttribute and it's use is disallowed by the SQL Server.
Best regards.
September 18th, 2009 at 1:49 pm
Thanks for the tip Alex. Appreciated!
December 4th, 2009 at 12:29 pm
Hi Alex.
What would you suggest as alternative when you want to do this kind of conversion within a CLR?
Regards.
Johan