简体   繁体   中英

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.
        //}
    }
}

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 .... */

Here is some code that worked for me:

SqlCommand ubCommand = new SqlCommand(sqltext);
ubCommand.Connection = ubConnection;
SqlDataReader ubReader = null;
ubReader = ubCommand.ExecuteReader();
ubReader.Read();
schednum = ToInt32(ubReader["ScheduleNum"].ToString());
int fieldNum;
lbl_schedule.Text = $"Schedule {schednum}";
for (i = 0; i < num_fields; i++)
{
 fieldNum = ubReader.GetOrdinal(fields[i]);
 values[i] = ubReader[fieldNum].ToString();
 types[i] = ubReader.GetFieldType(fieldNum);
 // Check types[i].Name for the results, like "String" or "Decimal"
}
ubReader.Close();
ubConnection.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM