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));
这篇关于返回的数据类型因表中的数据而异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回的数据类型因表中的数据而异


基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- rabbitmq 的 REST API 2022-01-01