返回的数据类型因表中的数据而异

时间:2012-11-09 10:26:57

标签: c# .net sql-server ado.net

我有一个包含两列的表 - [security_role_name]和security_role_cd。 security_role_cd的数据类型在Security_Role表中为smallint。

我有以下数据选择逻辑。返回的数据类型因数据情况而异: -

  1. 表格中没有数据
  2. 表格中的一条记录
  3. 问题

    1. 为什么数据类型在这些场景中有所不同
    2. 如何纠正
    3. 注意:目前我正在使用try..catch来实现此方案

      CODE

          private int GetNextRoleID(SqlConnection connection)
          {
              int? newRoleID = null;
              //string commandText = "SELECT  (MAX(security_role_cd)) AS [NewRoleID] FROM Security_Role ";
              string commandText = "SELECT  TOP 1 security_role_cd AS [NewRoleID] FROM Security_Role ORDER BY security_role_cd DESC";
              SqlCommand command = new SqlCommand(commandText, connection);
              command.CommandType = System.Data.CommandType.Text;
              SqlDataReader reader = command.ExecuteReader();
              if (reader.HasRows)
              {
                  while (reader.Read())
                  {
                      if (!reader.IsDBNull(0))
                      {
                          //newRoleID = Convert.ToInt32((reader.GetInt16(0)) + 1);
      
                          try
                          {
                              newRoleID = Convert.ToInt32(reader.GetInt16(0)) + 1;
                          }
                          catch
                          {
                              int result = (reader.GetInt32(0));
                              newRoleID = result + 1;
                          }
                      }
                  }
              }
              reader.Close();
      
              if (newRoleID == null)
              {
                  newRoleID = 1;
              }
      
              return (Convert.ToInt32(newRoleID));
      
          }
      

      参考:

      1. How do I get the SqlDbType of a column in a table using ADO.NET?

1 个答案:

答案 0 :(得分:2)

您可以查看reader.GetFieldType(0)。例如:

    int i;
    switch (Type.GetTypeCode(reader.GetFieldType(0)))
    {
        case TypeCode.Int16: i = reader.GetInt16(0); break;
        case TypeCode.Int32: i = reader.GetInt32(0); break;
        // TODO: any other cases you need to handle
        default: throw new NotSupportedException();
    }

或者更简单:

    int i = Convert.ToInt32(reader.GetValue(0));