Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

sql - Increase Primary Key value of existing table by 2 or any other number

I am using SQL Server. I have one table like this with some data where primary key is set to increase by 1 by default

CustomerId               CustomerName
-------------------------------------
 1                          John
 2                          David
 3                          Smith

Now I would like to make primary key increase by 2 instead of 1 automatically from now onwards without effecting existing data. What would be the safest way to do this ? For example: Now primary key would be 5 7 9 (with increment of 2) in this table.

 CustomerId               CustomerName
 --------------------------------------
     1                          John
     2                          David
     3                          Smith
     5                          Angelina
     7                          Johnny
     9                          Tom
question from:https://stackoverflow.com/questions/65661576/increase-primary-key-value-of-existing-table-by-2-or-any-other-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you cannot alter an identity column in SQL Server once it's been created, you'd really only have the option of creating a new table with the new desired structure (including the INT IDENTITY column that increments by 2), then copying over the existing data from the existing table, drop the existing table and rename the new table to the table name desired.

Of course, if you have any other tables referencing your existing table with a foreign key constraint, this would make things ever more challenging and involved.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...