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

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

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

  1. 表中没有数据
  2. 表中有一条记录

问题

  1. 为什么这些方案中的数据类型会有所不同
  2. 如何纠正它

注意 :目前我正在使用try..catch来满足这种情况

  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. 如何使用ADO.NET获取表中列的SqlDbType?

你可以看一下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));