-->

What happen in SQL 2005 when it run out of number

2020-06-03 03:56发布

问题:

What happen when SQL Server 2005 happen to reach the maximum for an IDENTITY column? Does it start from the beginning and start refilling the gap?

What is the behavior of SQL Server 2005 when it happen?

回答1:

You will get an overflow error when the maximum value is reached. If you use the bigint datatype with a maximum value of 9,223,372,036,854,775,807 this will most likely never be the case.

The error message you will get, will look like this:

Msg 220, Level 16, State 2, Line 10
Arithmetic overflow error for data type tinyint, value = 256.

(Source)

As far as I know MS SQL provides no functionality to fill the identity gaps, so you will either have to do this by yourself or change the datatype of the identity column.

In addition to this you can set the start value to the smallest negative number, to get an even bigger range of values to use.

Here is a good blog post about this topic.



回答2:

It will not fill in the gaps. Instead inserts will fail until you change the definition of the column to either drop the identity and find some other way of filling in the gaps or increase the size (go from int to bigint) or change the type of the data (from int to decimal) so that more identity values are available.



回答3:

You will be unable to insert new rows and will receive the error message listed above until you fix the problem. You can do this a number of ways. If you still have data and are using all the id's below the max, you will have to change the datatype. If the data is getting purged on a regular basis and you have a large gap that is not going to be used, you can reseed the identity number to the lowest number in that gap. For example,at a previous job,we were logging transactions. We had maybe 40-50 million per month, but we were purging everything older than 6 months, so every few years, the identity would get close to 2 Billion, but we would have nothing with an id below 1.5 billion, so we would reseed back to 0. Again it's possible that neither of these will work for you and you will have to find a different solution.



回答4:

If the identity column is an Integer, then your max is 2,147,483,647. You will get an overflow error if you exceed it.

If you think this is a risk, just use the BIGINT datatype, which gives you up to 9,223,372,036,854,775,807. Can't imagine a database table with that many rows.

Further discussion here. (Same link as xsl mentioned).



回答5:

In the event that you do hit the maximum number for you identity column, you can move the data from that table into a secondary table with a bigger identity column type and specify the starting value for that new identity value to be the maximum of the previous type. The new identity values will continue from that point.



回答6:

If you delete "old values" from time to time you just need to reset the seed using DBCC CHECKIDENT ('MyTable', RESEED, 0);