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

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

我有一个包含两列的表 - [security_role_name] 和 security_role_cd 。 Security_Role 表中 security_role_cd 的数据类型为 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. How do I get the SqlDbType of a column in a table using ADO.NET?

最佳答案

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

关于c# - 返回的数据类型因表中的数据而异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13306275/

相关文章:

c# - 气隙 .NET 代码签名应用程序将无法安装/运行

mysql - 具有不同产品名称的计数字段的 SQL 总和一次

c# - Screen.AllScreen 未提供正确的显示器计数

c# - asp : no file is created when logging a message 中的 Log4Net

c# - 使用 CustomAttributes 与 GetCustomAttributes() 的优势

sql - 单个查询删除并显示重复记录

c# - 单击一次安装 System.Data.SqlServerCe 出现问题?

模板参数的 C# void 等价物

c# - Context.User 在 Global.asax.Application_AuthenticateRequest 中分配后失去角色

.net - machine.config' 被拒绝