我有一个包含两列的表 - [security_role_name]和security_role_cd。 security_role_cd的数据类型在Security_Role表中为smallint。
我有以下数据选择逻辑。返回的数据类型因数据情况而异: -
问题
注意:目前我正在使用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));
}
参考:
答案 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));