简体   繁体   中英

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. To better understand what I meant, here is a screenshot of my 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.

Here is also part of the SQL script:

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

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 . 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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