如何将 t-sql 的“tinyint”转换为 c# 中的整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1922094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:52:07  来源:igfitidea点击:

How can you convert "tinyint" of t-sql to integer in c#?

c#sql-server

提问by Tebo

I have a tinyintcolumn in the database and I wish to convert it to Int32for an SqlDataReader.

tinyint在数据库中有一个列,我希望将其转换Int32SqlDataReader.

How do i go about it?

我该怎么做?

Edit #1

编辑 #1

I recently had to do this.

我最近不得不这样做。

int a = dataReader.GetByte(dr.GetOrdinal("ColumnName"));

#In Addition to Answer

#除了回答

SQL Server Data Type Mappings

SQL Server 数据类型映射

bigint           - GetInt64  
binary           - GetBytes  
int              - GetInt32  
money            - GetDecimal  
rowversion       - GetBytes  
smallint         - GetInt16  
tinyint          - GetByte  
uniqueidentifier - GetGuid   
...

For more info visit - SQL Server Data Type Mappings

有关更多信息,请访问 - SQL Server 数据类型映射

采纳答案by Jon Skeet

What does it normally come back as - byte? If so, just do an unbox and then a convert:

它通常返回什么 - 字节?如果是这样,只需进行拆箱,然后进行转换:

(int)(byte) reader["column"];

or just let the conversion happen naturally:

或者让转换自然发生:

int x = (byte) reader["column"];

or do the same with the strongly typed methods:

或对强类型方法执行相同操作:

int x = reader.GetByte(column);

Adjust this to sbyteor shortor whatever if I'm wrong about it mapping to byte. You could do the conversion at the SQL Server side, but I'd personally do it at the client side instead, and keep the SQL simpler.

调整这sbyte或者short或者如果我错了,它映射到什么byte。您可以在 SQL Server 端进行转换,但我个人会在客户端进行转换,并使 SQL 更简单。

回答by Rajesh Abraham

int RetValue;
RetValue = (int)(byte)dt.Rows[A][B]  // A = RowNo , B = 'tinyint' Column Name.

回答by Arnold Sandí Calderón

To get a tinyint from a sql table i do the following:

要从 sql 表中获取 tinyint,我执行以下操作:

retorno = Convert.ToInt32(dr.GetByte(dr.GetOrdinal("StepStatus")));

Where retorno is a int variable.

其中 retorno 是一个 int 变量。

I hope this help you.

我希望这对你有帮助。

回答by Pec1983

Use "SByte" works every-time For handling the Tiny Int problem

每次都使用“SByte”来处理 Tiny Int 问题