SqlServer中自动增量int主键的最大值

Lie*_*oen 8 sql-server

有最大值吗?SQL Server会在达到最大值时开始抛出SqlExceptions吗?你是如何解决的?(归档?)

从SQL Server资源中我可以看到最大值为2,147,483,647.我远非如此,但我只是好奇.

Mit*_*eat 9

a的最大值int确实是2,147,483,647.

如果您尝试超过最大大小,则会收到以下错误:

Msg 8115, Level 16, State 1, Line 2 
Arithmetic overflow error converting IDENTITY to data type int. 
Arithmetic overflow occurred.
Run Code Online (Sandbox Code Playgroud)

如果这还不够大,请使用bigint(9,223,372,036,854,775,807)


ser*_*iom 6

您可以使用这个小例子看到错误

use tempdb;

if OBJECT_ID('dbo.test', 'U') is not null drop table dbo.test

create table test
( id int identity not null,
  dummy int not null )
go

SET IDENTITY_INSERT dbo.test ON

insert into test(id, dummy) values(2147483647, 1)

SET IDENTITY_INSERT dbo.test OFF

insert into test(dummy) values(1)
Run Code Online (Sandbox Code Playgroud)

错误:

(1 row(s) affected)
Msg 8115, Level 16, State 1, Line 8
Arithmetic overflow error converting IDENTITY to data type int.
Arithmetic overflow occurred.
Run Code Online (Sandbox Code Playgroud)


Jør*_*ode 5

最大值由数据类型定义,而不是由IDENTITY修饰符定义.对于INT列,您已经计算出最大值.如果您需要具有更大范围的数据类型,BIGINT则是明显的选择,并且可以很好地标记它IDENTITY.

  • TINYINT:0到255
  • SMALLINT:-32768到32767
  • INT:-2147483648至2147483647
  • BIGINT:-9223372036854775808至9223372036854775807

我希望在达到最大值后尝试插入行时会引发错误,因为IDENTITY实现仍会尝试使用每个插入递增.

虽然将行存档到其他数据存储并开始重用标识符(DBCC CHECKIDENT (jobs, RESEED, 0)将重置计数器)当然是可能的,但它不是SQL Server提供的开箱即用的东西.您必须自己实现此逻辑,并且您还必须考虑重用标识符可能给您的应用程序带来哪些麻烦.例如,对于Web应用程序,旧URL会突然指向新文档还是返回404错误?