选择@@IDENTITY;沿着?
我正在抓取最后一个 rowid,并且正在执行此操作 select @@IDENTITY
pk = (long)cmd.ExecuteScalar();
我得到一个无效的类型转换,因为这是 int 而不是 long。为什么这不返回很长的值?我可以让它返回很长时间吗?
现在的解决方案是使用
pk = Convert.ToInt64(cmd.ExecuteScalar());
I am grabbing the last rowid and i am doing this select @@IDENTITY
pk = (long)cmd.ExecuteScalar();
I get an invalid typecast bc this is int instead of long. Why doesnt this return a long? can i make it return long?
Solution for now is to use
pk = Convert.ToInt64(cmd.ExecuteScalar());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用SCOPE_IDENTITY...这是< em>正确和十进制(38,0)无论如何...
但是,您应该注意@@IDENTITY也是decimal(38,0)
这是因为它必须包含任何可以自动编号的数据类型,例如decimal和bigint
编辑:
显然它是由 拆箱。 YMMV。
Use SCOPE_IDENTITY... which is correct and decimal(38,0) anyway...
However, you should note that @@IDENTITY is also decimal(38,0)
This is because it must encompass any datatype that can be autonumbered such as decimal and bigint
Edit:
Apparently it's caused by unboxing. YMMV.
在 SQL 查询中将
@@IDENTITY
转换为bigint
:In your SQL query convert
@@IDENTITY
tobigint
:也许可以选择 CAST(@@IDENTITY AS BIGINT) ?
SELECT CAST(@@IDENTITY AS BIGINT) maybe?
这不起作用,因为 ExecuteScalar 返回一个对象。这将是一个装箱整数。它只能拆箱为整数,其他任何内容都会生成类型转换异常。 C# 语言规范在第 4.3.2 章中没有浪费很多文字:
对非空值类型的拆箱操作包括首先检查对象实例是否是给定的装箱值 顺便说一句,
将其转换为 long 并不明智。在这么长的时间内,您所做的任何事情都最终会产生某种 SQL 错误。就像自己增加它一样。
This doesn't work because ExecuteScalar returns an object. That will be a boxed integer. It can only be unboxed to an integer, anything else will generate a type cast exception. The C# language specification doesn't waste a lot of words on it in chapter 4.3.2:
An unboxing operation to a non-nullable-value-type consists of first checking that the object instance is a boxed value of the given non-nullable-value-type, and then copying the value out of the instance.
Converting it to a long is not wise btw. There's nothing you could do with that long that wouldn't eventually produce some kind of SQL error. Like incrementing it yourself.
@@IDENTITY 返回一个小数(38,0),它又可以转换为任何其他整数类型,如下所示。
其中
int_data_type
是以下之一。数据类型
bigint
int
smallint
tinyint
请考虑它不会超过小数点(38,0)。
@@IDENTITY returns a decimal(38,0) that can in turn be cast as any other integer type like so.
where
int_data_type
is one of the following.Data type
bigint
int
smallint
tinyint
Consider though that it won't exceed the decimal(38,0).
而
ADO.NET
将NUMERIC(38)
(@@IDENTITY
的类型)转换为decimal
,这是最有效的方法开销最小的方法如下:但是请注意,
long
无法表示 MSSQL 的NUMERIC(38)
的整个范围。Whereas
ADO.NET
translatesNUMERIC(38)
—the type of@@IDENTITY
—asdecimal
, the most efficient method with the least overhead is the following:But observe that a
long
cannot represent the entire range of MSSQL'sNUMERIC(38)
.