Datatype returned varies based on data in table(返回的数据类型因表中的数据而异)
问题描述
我有一个包含两列的表 - [security_role_name] 和 security_role_cd .security_role_cd 的数据类型是 Security_Role 表中的 smallint.
I have a table with two column - [security_role_name] and security_role_cd . Datatype for security_role_cd is smallint in Security_Role table.
我有以下数据选择逻辑.返回的数据类型因数据的场景而异:-
I have following data selection logic. The datatype returned varies based on the scenario of data:-
- 表格中没有数据
 - 表格中有一条记录
 
问题
- 为什么在这些场景中数据类型会有所不同
 - 如何改正
 
注意:目前我正在使用 try..catch 来满足这种情况
Note: Currently i am using try..catch to meet this scenario
代码
    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));
    }
参考:
- 如何使用 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));
                        这篇关于返回的数据类型因表中的数据而异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回的数据类型因表中的数据而异
				
        
 
            
        - Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
 - 在 LINQ to SQL 中使用 contains() 2022-01-01
 - 在 C# 中异步处理项目队列 2022-01-01
 - 带问号的 nvarchar 列结果 2022-01-01
 - 使用 rss + c# 2022-01-01
 - 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
 - C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
 - Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
 - 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
 - CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
 
						
						
						
						
						