Usable Asp.Net

Little things that make Asp.Net more usable

Programmatically determining the sqlDbType of a field

I found this remarkable info in a newsgroup post from David Sceppa from Microsoft:

You can build a SqlCommand to query the table and retrieve this schema information from the SqlDataReader through its GetSchemaTable method.  This method returns a DataTable of schema information. Each row in the DataTable corresponds to a column in the resultset for the original query. The DataTable of schema information includes columns for column name, data type, etc. There's a column called ProviderType that contains an integer, which you can cast to SqlDbType.

Here's some code that should help:

Visual Basic .NET:
  Dim strConn, strSQL As String
  strConn = "Data Source=(local)\NetSDK;Initial Catalog=Northwind;" & _
            "Trusted_Connection=Yes;"
  Dim cn As New SqlConnection(strConn)
  cn.Open()
  strSQL = "SELECT OrderDate FROM Orders"
  Dim cmd As New SqlCommand(strSQL, cn)
  Dim rdr As SqlDataReader
  rdr = cmd.ExecuteReader(CommandBehavior.SchemaOnly)
  Dim tbl As DataTable = rdr.GetSchemaTable()
  rdr.Close()
  cn.Close()
  Dim intOrderDateType As Integer
  intOrderDateType = CType(tbl.Rows(0)("ProviderType"), Integer)
  Dim typOrderDateType As SqlDbType
  typOrderDateType = CType(intOrderDateType, SqlDbType)
  Console.WriteLine("ProviderType = " & intOrderDateType)
  Console.WriteLine("SqlDbType = " & typOrderDateType.ToString())


Visual C# .NET:
  string strConn, strSQL;
  strConn = @"Data Source=(local)\NetSDK;Initial Catalog=Northwind;" +
             "Trusted_Connection=Yes;";
  SqlConnection cn = new SqlConnection(strConn);
  cn.Open();
  strSQL = "SELECT OrderDate FROM Orders";
  SqlCommand cmd = new SqlCommand(strSQL, cn);
  SqlDataReader rdr;
  rdr = cmd.ExecuteReader(CommandBehavior.SchemaOnly);
  DataTable tbl = rdr.GetSchemaTable();
  rdr.Close();
  cn.Close();
  int intOrderDateType;
  intOrderDateType = (int) tbl.Rows[0]["ProviderType"];
  SqlDbType typOrderDateType;
  typOrderDateType = (SqlDbType) intOrderDateType;
  Console.WriteLine("ProviderType = " + intOrderDateType);
  Console.WriteLine("SqlDbType = " + typOrderDateType.ToString());

Posted: Dec 20 2006, 03:34 PM by egoldin | with 6 comment(s)
Filed under:

Comments

Daniel Grad said:

Thank you so much... I was going crazy trying to find this
# June 14, 2007 5:14 AM

DG said:

Thanks so much!!  I also needed this!

# November 5, 2007 4:28 PM

BH said:

Very grateful.

Wasted about 3 hours Googling before I came across this !

Thanks again.

# February 1, 2008 6:16 PM

Ron said:

Excellent ! Like the others I was searching for this for hours.

# April 4, 2008 5:48 AM

manjuantha said:

Thanks a ton !

It saved us so much time ...thank u

# May 16, 2008 3:49 AM

Jon B said:

Yes, thanks, that did the trick.

# July 17, 2008 12:12 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)