为什么 select SCOPE_IDENTITY() 返回小数而不是整数?
所以我有一个以标识列作为主键的表,因此它是一个整数。那么,为什么 SCOPE_IDENTITY()
总是向我的 C# 应用程序返回十进制值而不是 int ?这真的很烦人,因为十进制值不会在 C# 中隐式转换为整数,这意味着我现在必须重写一堆东西并有很多辅助方法,因为我使用 SQL Server 和 Postgres,其中 Postgres 确实返回一个整数等效函数..
为什么 SCOPE_IDENTITY()
不只返回一个普通整数?是否有人通常使用十进制/非同一值作为主键?
So I have a table with an identity column as the primary key, so it is an integer. So, why does SCOPE_IDENTITY()
always return a decimal value instead of an int to my C# application? This is really annoying since decimal values will not implicitly convert to integers in C#, which means I now have to rewrite a bunch of stuff and have a lot of helper methods because I use SQL Server and Postgres, which Postgres does return an integer for the equivalent function..
Why does SCOPE_IDENTITY()
not just return a plain integer? Are there people out there that commonly use decimal/non-identity values for primary keys?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 SQL Server 中,
IDENTITY
属性可以分配给tinyint
、smallint
、int
、bigint< /code>、
decimal(p, 0)
或numeric(p, 0)
列。因此,SCOPE_IDENTITY 函数必须返回包含上述所有内容的数据类型。正如前面的答案所说,只需在返回之前将其转换为服务器上的
int
,然后 ADO.NET 将按照您的预期检测其类型。In SQL Server, the
IDENTITY
property can be assigned totinyint
,smallint
,int
,bigint
,decimal(p, 0)
, ornumeric(p, 0)
columns. Therefore theSCOPE_IDENTITY
function has to return a data type that can encompass all of the above.As previous answers have said, just cast it to
int
on the server before returning it, then ADO.NET will detect its type as you expect.难道你不能在从查询或存储过程返回它之前强制转换它(SP 总是返回 int 无论如何,但也许你正在使用输出参数)?
就像 SELECT CAST(SCOPE_IDENTITY() AS INT) AS LAST_IDENTITY
为什么要这样做呢?可能是为了更灵活并处理更大的数字。
Can't you just cast it before returning it from your query or stored proc (SPs alway return int anyway, but maybe you are using an output parameter)?
Like
SELECT CAST(SCOPE_IDENTITY() AS INT) AS LAST_IDENTITY
And why it does this? Probably to be more flexible and handle larger numbers.
尝试使用这个,你会得到一个整数:
try using this and you'll get an integer back:
范围标识返回值是十进制(38,0)
CAST它,使用 OUTPUT 子句,或分配给客户端的输出参数而不是 SELECT SCOPE_IDENTITY()
Scope identity return value is decimal(38,0)
CAST it, use the OUTPUT clause, or assign to an output parameter rather than
SELECT SCOPE_IDENTITY()
to the client这不是所问问题的确切答案,但按照上面答案的脉络,(在 T-SQL - MS SQLServer 中)怎么样:
select Convert(bigint, SCOPE_IDENTITY())
This isn't an exact answer to the question as asked, but in the vein of the answers above, how about (in T-SQL - MS SQLServer):
select convert(bigint, SCOPE_IDENTITY())