Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get data type of a SQL Server column using C#

I'm not sure what exactly I'm doing wrong, can someone correct it please? I need to determine the type of a retrieved column from a SQL Server database using C#.

Say, I have this:

SqlConnection cn = new SqlConnection("Sql Connection String");
SqlCommand cmd = new SqlCommand("SELECT * FROM [TableName]", cn);
SqlDataReader rdr = cmd.ExecuteReader();

while (rdr.Read())
{
    for (int c = 0; c < rdr.VisibleFieldCount; c++)
    {
        System.Type type = rdr.GetFieldType(c);

        //So can I do this? (Pseudo-code)
        //switch(type)
        //{
        //case string:
        //case int:
        //case DateTime:
        //etc.
        //}
    }
}
like image 668
ahmd0 Avatar asked Mar 15 '12 01:03

ahmd0


People also ask

How do I find the datatype of a column in SQL?

You can get the MySQL table columns data type with the help of “information_schema. columns”. SELECT DATA_TYPE from INFORMATION_SCHEMA. COLUMNS where table_schema = 'yourDatabaseName' and table_name = 'yourTableName'.

How do I find the data type of a variable in SQL Server?

Use TYPE_NAME() to Get the Name of a Data Type in SQL Server In SQL Server, you can use the TYPE_NAME() function to return the name of a data type, based on its ID. This can be useful when querying a system view such as sys.

How do I find the column data type in SQL Server Management Studio?

Once you connect to a database in SSMS, you can view these data types by navigating to Programmability-> Types->System Data Types.

How do I get column properties in SQL Server?

To define SQL Server table column properties: Right-click a column in the Model Explorer and click Properties. The SQL Server Table Column Editor opens. Select the table from the Table drop-down to define the columns that are available for the table.


1 Answers

You can do the following:

/* ... code .... */

System.Type type = rdr.GetFieldType(c);

switch (Type.GetTypeCode(type))
{
    case TypeCode.DateTime:
        break;
    case TypeCode.String:
        break;
    default: break;
}

/* ... code .... */
like image 68
Alex Avatar answered Oct 27 '22 15:10

Alex