使用C#获取SQL Server列的数据类型

时间:2012-03-15 01:10:37

标签: c# asp.net sql sqldatatypes

我不确定我到底做错了什么,有人可以纠正吗?我需要使用C#从SQL Server数据库中确定检索列的类型。

说,我有这个:

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

2 个答案:

答案 0 :(得分:10)

您可以执行以下操作:

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

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

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

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

答案 1 :(得分:0)

以下是对我有用的代码:

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();