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.
//}
}
}
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'.
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.
Once you connect to a database in SSMS, you can view these data types by navigating to Programmability-> Types->System Data Types.
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.
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 .... */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With