简体   繁体   English

如何在SQL Server中重置自动增量?

[英]How to reset auto-increment in SQL Server?

I've been having this problem with my database where it kept on incrementing the id column even though it has been removed. 我的数据库一直存在这个问题,即使它已被删除,它仍继续增加id列。 To better understand what I meant, here is a screenshot of my gridview: 为了更好地理解我的意思,这是我的gridview的屏幕截图:

在此处输入图片说明

As you can see from the id column, everything is fine from 11 - 16. but it suddenly skipped from 25 - 27. What i want to happen is, when i remove an item, i want it to start from the last id which is 16. So the next id should be 17. I hope this makes sense for you guys. 从id列中可以看到,从11-16一切都很好,但是从25-27突然跳了起来。我想发生的是,当我删除一个项目时,我希望它从最后一个id开始16.所以下一个id应该是17.我希望这对你们有意义。

Here is also part of the SQL script: 这也是SQL脚本的一部分:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[guitarItems]
(
    [id] [int] IDENTITY(1,1) NOT NULL,
    [type] [varchar](50) NOT NULL,
    [brand] [varchar](50) NOT NULL,
    [model] [varchar](50) NOT NULL,
    [price] [float] NOT NULL,
    [itemimage1] [varchar](255) NULL,
    [itemimage2] [varchar](255) NULL,
    [description] [text] NOT NULL,
    [necktype] [varchar](100) NOT NULL,
    [body] [varchar](100) NOT NULL,
    [fretboard] [varchar](100) NOT NULL,
    [fret] [varchar](50) NOT NULL,
    [bridge] [varchar](100) NOT NULL,
    [neckpickup] [varchar](100) NOT NULL,
    [bridgepickup] [varchar](100) NOT NULL,
    [hardwarecolor] [varchar](50) NOT NULL,

    PRIMARY KEY CLUSTERED ([id] ASC)
 ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
 GO

 SET ANSI_PADDING OFF
 GO

You can use: 您可以使用:

DBCC CHECKIDENT ("YourTableNameHere", RESEED, 1);

Before using it, visit link: https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql 在使用它之前,请访问链接: https : //docs.microsoft.com/zh-cn/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql

Primary autoincrement keys in the database are used to uniquely identify a given row and shouldn't be given any business meaning. 数据库中的主自动增量键用于唯一地标识给定的行,并且不应赋予任何业务含义。 So leave the primary key as it is and add another column like guitarItemsId . 因此,保留主键不变,然后添加另一列,例如guitarItemsId Then when you delete a record from the database you may want to send an additional UPDATE statement in order to decrease the guitarItemsId column of all rows that have the guitarItemsId greater than the one you are currently deleting. 然后,当您从数据库中删除一条记录时,您可能希望发送一条附加的UPDATE语句,以减少所有GuitarItemsId大于当前删除的行的guitarItemsId列。

Also, remember that you should never modify the value of a primary key in a relational database because there could be other tables that reference it as a foreign key and modifying it might violate the referential constraints. 另外,请记住,永远不要在关系数据库中修改主键的值,因为可能会有其他表将其引用为外键,并且对其进行修改可能会违反引用约束。

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

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