删除后重置 SQL Server 中的自动增量

发布于 2024-07-13 15:50:22 字数 221 浏览 8 评论 0原文

我已从 SQL Server 数据库的表中删除了一些记录。

表中的 ID 如下所示:

99 100 101 1200 第1201章

我想删除后面的记录(ID > 1200),然后我想重置自动增量,这样下一个自动生成的ID将为102。所以我的记录是连续的,有没有办法在SQL中做到这一点服务器?

I've deleted some records from a table in a SQL Server database.

The IDs in the table look like this:

99
100
101
1200
1201...

I want to delete the later records (IDs >1200), then I want to reset the auto increment so the next autogenerated ID will be 102. So my records are sequential, Is there a way to do this in SQL Server?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

耀眼的星火 2024-07-20 15:50:23

要将数据库中的每个键重置为从最后一个最高键的最大值自动递增:

Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED, 0)'

Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED)'

To reset every key in the database to autoincrement from the max of the last highest key:

Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED, 0)'

Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED)'
马蹄踏│碎落叶 2024-07-20 15:50:23

如果您只想重置主键/序列以在 SQL Server 中以您想要的序列开始,这里是解决方案 -

ID:

99 100 101 1200 1201...

  1. 删除 ID >= 1200 的行。(如果您有与这些约束相关的外键约束,则必须小心处理或删除这些约束才能删除它。)
  2. 现在您想要确保您知道 MAX ID 以确保:

将 @max_id 声明为 int = (SELECT MAX(your_column_name) FROM
你的表)+1;

(注意:+1 在最大值后启动 ID 序列)

  1. 重新启动序列:

exec('改变序列 your_column_name 用 ' + @max_id 重新启动);

(注:with后面必须有空格)
现在,新记录将以 102 作为 ID 开头。

If you just want to reset the primary key/sequence to start with a sequence you want in a SQL server, here's the solution -

IDs:

99 100 101 1200 1201...

  1. Drop rows with IDs >= 1200. (Be careful if you have foreign key constraints tied to these which has to be dealed with or deleted too to be able to delete this.)
  2. Now you want to make sure you know the MAX ID to be sure:

declare @max_id as int = (SELECT MAX(your_column_name) FROM
your_table)+1;

(Note: +1 to start the ID sequence after max value)

  1. Restart your sequence:

exec('alter sequence your_column_name restart with ' + @max_id);

(Note: Space after with is necessary)
Now new records will start with 102 as the ID.

裂开嘴轻声笑有多痛 2024-07-20 15:50:23

我知道这是一个老问题。 然而,我正在寻找类似的 MySQL 解决方案,并且出现了这个问题。

对于那些正在寻找 MySQL 解决方案的人,您需要运行以下查询:

// important!!! You cannot reset the counter to a value less than or equal to the value that is currently in use. For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum AUTO_INCREMENT column value plus one.
   
ALTER TABLE <your-table-name> AUTO_INCREMENT = 100

文档

I know this is an old question. However, I was looking for a similar solution for MySQL and this question showed up.

for those who are looking for MySQL solution, you need to run this query:

// important!!! You cannot reset the counter to a value less than or equal to the value that is currently in use. For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum AUTO_INCREMENT column value plus one.
   
ALTER TABLE <your-table-name> AUTO_INCREMENT = 100

documentation

羞稚 2024-07-20 15:50:23

我认为最好的一个是:

declare @max int  
select @max = isnull(max(key),1) from table  
dbcc checkident(table,reseed,@max)

I think the best one is:

declare @max int  
select @max = isnull(max(key),1) from table  
dbcc checkident(table,reseed,@max)
最后的乘客 2024-07-20 15:50:22

发出以下命令将 mytable 重新设定为从 1 开始:

DBCC CHECKIDENT (mytable, RESEED, 0)

请参阅在线书籍(BOL、SQL 帮助)中了解相关内容。 另请注意,您的记录不得高于您设置的种子。

Issue the following command to reseed mytable to start at 1:

DBCC CHECKIDENT (mytable, RESEED, 0)

Read about it in the Books on Line (BOL, SQL help). Also be careful that you don't have records higher than the seed you are setting.

烟雨凡馨 2024-07-20 15:50:22
DBCC CHECKIDENT('databasename.dbo.tablename', RESEED, number)

如果 number = 0 那么在下一个插入中自动增量字段将包含值 1

如果 number = 101 那么在下一个插入中自动增量字段将包含值 102

一些附加信息...可能对您有用

在上述查询中提供自动增量 number 之前,您必须确保现有表的自动增量列包含小于 number 的值。

要从表(table1)中获取列(column_name)的最大值,可以使用以下查询

 SELECT MAX(column_name) FROM table1
DBCC CHECKIDENT('databasename.dbo.tablename', RESEED, number)

if number = 0 then in the next insert the auto increment field will contain value 1

if number = 101 then in the next insert the auto increment field will contain value 102

Some additional info... May be useful for you

Before giving auto increment number in above query, you have to make sure your existing table's auto increment column contain values less that number.

To get the maximum value of a column(column_name) from a table(table1), you can use following query

 SELECT MAX(column_name) FROM table1
眼角的笑意。 2024-07-20 15:50:22

半白痴证明:

declare @max int;  
select @max = max(key) from table;  
dbcc checkident(table,reseed,@max)

http://sqlserverplanet。 com/tsql/using-dbcc-checkident-to-reseed-a-table-after-delete

semi idiot-proof:

declare @max int;  
select @max = max(key) from table;  
dbcc checkident(table,reseed,@max)

http://sqlserverplanet.com/tsql/using-dbcc-checkident-to-reseed-a-table-after-delete

何止钟意 2024-07-20 15:50:22

如果您使用 MySQL,请尝试以下操作:

ALTER TABLE tablename AUTO_INCREMENT = 1

If you're using MySQL, try this:

ALTER TABLE tablename AUTO_INCREMENT = 1
北座城市 2024-07-20 15:50:22

我想到了。 它是:

 DBCC CHECKIDENT ('tablename', RESEED, newseed)

I figured it out. It's:

 DBCC CHECKIDENT ('tablename', RESEED, newseed)
帅气尐潴 2024-07-20 15:50:22

删除数据库中的所有表并重新设定种子。

    USE [DatabaseName]
    EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"       -- Disable All the constraints
    EXEC sp_MSForEachTable "DELETE FROM ?"    -- Delete All the Table data
    Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED, 0)' -- Reseed All the table to 0
    Exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"  -- Enable All  the constraints back

-- You may ignore the errors that shows the table without Auto increment field.

Delete and Reseed all the tables in a database.

    USE [DatabaseName]
    EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"       -- Disable All the constraints
    EXEC sp_MSForEachTable "DELETE FROM ?"    -- Delete All the Table data
    Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED, 0)' -- Reseed All the table to 0
    Exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"  -- Enable All  the constraints back

-- You may ignore the errors that shows the table without Auto increment field.
別甾虛僞 2024-07-20 15:50:22

根据接受的答案,对于遇到类似问题的人,具有完整的架构限定:

([MyDataBase].[MySchemaName].[MyTable])... 导致错误,您需要在该数据库的上下文中

也就是说,以下内容将引发错误:

DBCC CHECKIDENT ([MyDataBase].[MySchemaName].[MyTable], RESEED, 0)

用单引号将完全限定的表名括起来:

DBCC CHECKIDENT ('[MyDataBase].[MySchemaName].[MyTable]', RESEED, 0)

Based on the accepted answer, for those who encountered a similar issue, with full schema qualification:

([MyDataBase].[MySchemaName].[MyTable])... results in an error, you need to be in the context of that DB

That is, the following will throw an error:

DBCC CHECKIDENT ([MyDataBase].[MySchemaName].[MyTable], RESEED, 0)

Enclose the fully-qualified table name with single quotes instead:

DBCC CHECKIDENT ('[MyDataBase].[MySchemaName].[MyTable]', RESEED, 0)
时光病人 2024-07-20 15:50:22

有几个答案建议使用这样的语句:

DBCC CHECKIDENT (mytable, RESEED, 0)

但是OP说“删除了一些记录”,这可能不是全部,所以0值并不总是正确的。 另一个答案建议自动查找最大当前值并重新播种到该值,但是如果表中没有记录,则会遇到麻烦,因此 max() 将返回 NULL。 一条评论建议仅使用

DBCC CHECKIDENT (mytable)

重置值,但另一条评论正确地指出这只会将值增加到表中已有的最大值; 如果该值已经高于表中的最大值,则这不会减少该值,这正是OP想要做的。

更好的解决方案结合了这些想法。 第一个 CHECKIDENT 将值重置为 0,第二个将其重置为表中当前的最高值,以防表中存在记录:

DBCC CHECKIDENT (mytable, RESEED, 0)
DBCC CHECKIDENT (mytable)

正如多个注释所示,请确保其他表中没有外键指向已删除的记录。 否则,这些外键将指向您在重新播种表后创建的记录,这几乎肯定不是您想要的。

Several answers recommend using a statement something like this:

DBCC CHECKIDENT (mytable, RESEED, 0)

But the OP said "deleted some records", which may not be all of them, so a value of 0 is not always the right one. Another answer suggested automatically finding the maximum current value and reseeding to that one, but that runs into trouble if there are no records in the table, and thus max() will return NULL. A comment suggested using simply

DBCC CHECKIDENT (mytable)

to reset the value, but another comment correctly stated that this only increases the value to the maximum already in the table; this will not reduce the value if it is already higher than the maximum in the table, which is what the OP wanted to do.

A better solution combines these ideas. The first CHECKIDENT resets the value to 0, and the second resets it to the highest value currently in the table, in case there are records in the table:

DBCC CHECKIDENT (mytable, RESEED, 0)
DBCC CHECKIDENT (mytable)

As multiple comments have indicated, make sure there are no foreign keys in other tables pointing to the deleted records. Otherwise those foreign keys will point at records you create after reseeding the table, which is almost certainly not what you had in mind.

不疑不惑不回忆 2024-07-20 15:50:22

我想添加这个答案,因为当您使用表架构时,DBCC CHECKIDENT 方法会产生问题。 使用它来确定:

DECLARE @Table AS NVARCHAR(500) = 'myschema.mytable';
DBCC CHECKIDENT (@Table, RESEED, 0);

如果您想检查操作是否成功,请

SELECT IDENT_CURRENT(@Table);

在上面的示例中使用它应该输出 0

I want to add this answer because the DBCC CHECKIDENT-approach will product problems when you use schemas for tables. Use this to be sure:

DECLARE @Table AS NVARCHAR(500) = 'myschema.mytable';
DBCC CHECKIDENT (@Table, RESEED, 0);

If you want to check the success of the operation, use

SELECT IDENT_CURRENT(@Table);

which should output 0 in the example above.

嘿咻 2024-07-20 15:50:22

一般来说,您不想这样做。 重新设定种子可能会造成数据完整性问题。 它实际上仅适用于需要清除所有测试数据并重新开始的开发系统。 如果尚未删除所有相关记录(并非每个应该存在外键关系的表!),则不应在生产系统上使用它。 这样做可能会造成混乱,尤其是如果您打算在每次删除后定期执行此操作。 担心身份字段值中的差距是一个坏主意。

You do not want to do this in general. Reseed can create data integrity problems. It is really only for use on development systems where you are wiping out all test data and starting over. It should not be used on a production system in case all related records have not been deleted (not every table that should be in a foreign key relationship is!). You can create a mess doing this and especially if you mean to do it on a regular basis after every delete. It is a bad idea to worry about gaps in you identity field values.

护你周全 2024-07-20 15:50:22

那这个呢?

ALTER TABLE `table_name`
  MODIFY `id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;

这是将自动增量更改为 0 或任何您想要的数字的快速而简单的方法。 我通过导出数据库并自己阅读代码来解决这个问题。

您也可以这样写,使其成为单行解决方案:

ALTER TABLE `table_name` MODIFY `id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;

What about this?

ALTER TABLE `table_name`
  MODIFY `id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;

This is a quick and simple way to change the auto increment to 0 or whatever number you want. I figured this out by exporting a database and reading the code myself.

You can also write it like this to make it a single-line solution:

ALTER TABLE `table_name` MODIFY `id` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=0;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文