how to Reset AutoIncrement in SQL Server after all data Deleted

人盡茶涼 提交于 2019-12-02 08:28:25

问题


i got a function in sql that generate sequential series of alphanumeric no.like (c000,c0001 .......) , which is working good . but when i deleted all data in table , it starts from last generated no. i want it to reset its value from "c0000" .

code is as follows :-

create table Customers
(
dbID int identity not null primary key,
CustomerName varchar(100)
)

 create function CustomerNumber (@id int) 
  returns char(5) 
  as 
 begin 
 return 'C' + right('0000' + convert(varchar(10), @id), 4) 
  end

  alter table Customers add CustomerNumber as dbo.CustomerNumber(dbID)

thanks in advance....

EDIT 1 -

how to update it to increment based on last value . means if last entry having no. c0053 , and i deleted this record , so when next entry added it should have value "C0053" not "C0054".

thanks


回答1:


TRUNCATE TABLE

Removes all rows from a table or specified partitions of a table, without logging the individual row deletions. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause; however, TRUNCATE TABLE is faster and uses fewer system and transaction log resources.

TRUNCATE TABLE Customers

or remove your in build function.




回答2:


Truncate Table Command is good way to reset Identity, but there is other command also to reset Identity after deletion of records.

DBCC CHECKIDENT (TableName, RESEED, 0)

After Deleting you can use this command to reset Identity to 0.




回答3:


My suggestion is instead of deleting all rows of data why dont you truncate the table.

If you are truncate the table it automatically reset your auto increment to 0

TRUNCATE TABLE your_table_name;

This example would truncate the table and remove all records from that table. and rest your auto increment too.

The SQL TRUNCATE TABLE command is used to delete complete data from an existing table

Try this way. May help you.



来源:https://stackoverflow.com/questions/42871201/how-to-reset-autoincrement-in-sql-server-after-all-data-deleted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!