Getschema ("Columns") + returns a DataType;

I have this code

using (SqlConnection conn = new SqlConnection(ConnectionString))
                    {
                        conn.Open();
                        DataTable Databases = conn.GetSchema("Databases");
                        DataTable Tables = conn.GetSchema("Tables");
                        DataTable Columns = conn.GetSchema("Columns");
                        conn.close();
                     }

I need to return the data type by reading the string value in the "DATA_TYPE" column

 foreach (DataRow row in Columns.Rows)
                if (row["TABLE_NAME"].ToString() == tableName)
                {
                    if (fName == row["COLUMN_NAME"].ToString())
                    {
                      //return Datatype 
                      var x = row["DATA_TYPE"];
                    }
                }

//// if (row ["DATA_TYPE"] == "int"), how can I set var x by DataType (Int) or how to get the data type by name, which is in the string ["DATA_TYPE"] ??! !

+5
source share
1 answer

there would be a solution to create a dictionary matching sql types with .net types:

Dictionary<string, Type> sqlToNetTypes;

and populate it with all the possible types that you can find in the "DATA_TYPE" column and their .NET equivalent:

sqlToNetTypes.Add("int", typeof(int));
sqlToNetTypes.Add("varchar", typeof(sting));
sqlToNetTypes.Add("datetime", typeof(DateTime));
sqlToNetTypes.Add("bit", typeof(bool));
sqlToNetTypes.Add("numeric", typeof(float));//or double or decimal as you like...
...

then in the helper method:

Type GetNETType(string sqlType)
{
    if(sqlToNetTypes.ContainsKey(sqlType))
    {
        return sqlToNetTypes[sqlType];
    }else
    {
        return typeof(object); //generic type
    }
}

and use it as follows:

foreach (DataRow row in Columns.Rows)
    if (row["TABLE_NAME"].ToString() == tableName)
    {
        if (fName == row["COLUMN_NAME"].ToString())
        {
            //return Datatype 
            var x = GetNETType(row["DATA_TYPE"]);
        }
    }
+4
source

All Articles