简体   繁体   English

如何重新编号 T-SQL 的系统自增标识列?

[英]How to re-number T-SQL's system auto-increment Identity column?

I have an auto-increment primary key in a SQL table lets say table look like this:我在 SQL 表中有一个自动增量主键,可以说表如下所示:

CREATE TABLE [Table] (--Identifier contains a space and uses a reserved keyword.
    [ID] [int] IDENTITY(1,1) NOT NULL ,
    [Name] [varchar](50) NULL, 
    CONSTRAINT [PK__Table] PRIMARY KEY CLUSTERED ([ID] ASC)
);

ID  |  Name|
1     John
2     Jack
3     Bill 
4     Joe

Then I delete row 2 Jack:然后我删除第 2 行杰克:

ID  |  Name|
1     John
3     Bill 
4     Joe

And what I want to achieve is to change id column so the table will look like this我想要实现的是更改 id 列,使表看起来像这样

ID  |  Name|
1     John
2     Bill 
3     Joe

Is there a way to do it?有没有办法做到这一点?

I will never do that but you can:我永远不会这样做,但你可以:

  1. create a new autoincrement primary key named ID2创建一个名为 ID2 的新自动增量主键
  2. delete ID column删除 ID 列
  3. rename ID2 column as ID将 ID2 列重命名为 ID

Quick and dirty way to do it is, (my way) -->快速而肮脏的方法是,(我的方式)-->

select * into yournewtable from youroldtable order by yourIdentityColumn;

Then, open up yournewtable's design, make sure yourIdentityColumn is Identity(1,1).然后,打开 yournewtable 的设计,确保 yourIdentityColumn 是 Identity(1,1)。

Then, drop youroldtable.然后,放下你的旧表。

Then, rename yournewtable to youroldtable!然后,将 yournewtable 重命名为 youroldtable! ta-da!达达!

Set identity_insert Table off;
Update Table set ID = 3 where ID = 4;
...
Set identity_insert Table on;

Where Table name is Table其中表名是

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM