Updating identity column in SQL Server and setting the seed starting value

此生再无相见时 提交于 2021-01-28 19:37:14

问题


I have a table filled with data and one of the columns - TrackingNumber - is an integer value. I have gotten a request to change it to auto-increment and to have it start the identity seed at 1000000. I know that I cannot alter a column to be an identity column in an existing table with data, so I have two options: either create an entirely new table and then move data from the old table into that new table or add an new identity column and update it with data from the old column.

The problem is that I need to retain all the existing values in column TrackingNumber. I have tried the following:

1) ALTER TABLE [dbo].[Table1]
ADD [TrackingNumber2] [bigint] IDENTITY (1000000, 1) NOT NULL

2) UPDATE [dbo].[Table1]
SET [TrackingNumber2]=[TrackingNumber]

3) ALTER TABLE [dbo].[Table1]
DROP COLUMN [TrackingNumber] 
GO

4) EXEC sp_rename 'Table1.TrackingNumber2', 'TrackingNumber','COLUMN'

I got an error on step 2 - Updating new column with the value from the old column: "Cannot update identity column 'TrackingNumber2'"

Can anyone recommend a workaround?


回答1:


You just need to set identity_insert on for this table so you can update the values. Make sure you turn it back off when you complete the update. :)

https://msdn.microsoft.com/en-us/library/ms188059.aspx




回答2:


Are you sure you need to use an identity column? There are alternatives. For example, since SQL Server 2012 (and azure, too), there are these things called sequences. You can define a sequence to start at any number you like:

create sequence dbo.TrackingSequence
as int
  start with 1000000
  increment by 1
  no maxvalue
  no cycle
  no cache

Then, you can alter the table such that the default value for the column in question defaults from the sequence:

alter table dbo.MyTable 
  add constraint [MyTable.TrackingNumber.Default.TrackingSequence]
    default( next value for dbo.TrackingSequence ) for TrackingNumber

(If the column already has a default value, you need to remove that first - in a separate statement.)

A sequence works a lot like an identity, but you don't have to disrupt existing values or the column definition per se.

The only trick is to remember to not specify the value for TrackingNumber, and let the DB do its thing.

Sequences are cool in that you can have one sequence that is used by multiple tables, giving you somewhat shorter db-wide unique IDs than alternatives in the past. For such an application, you'd probably be better off with a bigint column - or know that the tables in question aren't going to be terribly long.




回答3:


I ended up creating a new table and moving data in there



来源:https://stackoverflow.com/questions/32362800/updating-identity-column-in-sql-server-and-setting-the-seed-starting-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!