you can CHECKIDENT To Reset Seed
DBCC CHECKIDENT
(
table_name
[ , { NORESEED | { RESEED [ , new_reseed_value ] } } ]
)
[ WITH NO_INFOMSGS ]
Example
DBCC CHECKIDENT ('TAble', reseed,0)
--
Example Query
You can to insert the basic data with the following codes
first create one table after insert data to table
step to step i show data and Remove data for Show Details for understand Code
Result code : Create Table with rest seed Id
I used dmv sys.identity_columns that table has identity
--Create Table
DROP TABLE IF EXISTS ExampleTable
create table ExampleTable (Id Bigint identity(1,1), Name nvarchar(10))
--Insert to ExampleTable and Delete and Show identity
insert into ExampleTable (Name)
select 'Test1' as NAme union all select 'Test2' as NAme
select * from ExampleTable
| Id | Name |
| -------- | -----|
| 1 |Test1 |
| 2 |Test2 |
delete from ExampleTable
insert into ExampleTable (Name) select 'Test3' as NAme
select * from ExampleTable
| Id | Name |
| -------- | -----|
| 3 |Test3 |
delete from ExampleTable
First check data
if Table has not data use seed table
if Table has data use use Max id
after change seed with CHECKIDENT
--Find seedTable
declare @reseed int=0
if(not exists( select top 1 * from ExampleTable))
begin
SELECT
@reseed=cast( seed_value as int)
FROM sys.tables tables
JOIN sys.identity_columns identity_columns
ON tables.object_id=identity_columns.object_id
where
tables.name='ExampleTable'
and OBJECT_SCHEMA_NAME(tables.object_id, db_id())='dbo'
set @reseed=@reseed -1
end
else
begin
--if Table Has Data and use Max id For seed
set @reseed=(select top 1 id from ExampleTable order by id desc)
end
DBCC CHECKIDENT ('ExampleTable', reseed,@reseed)
insert into ExampleTable
(Name)
select 'Test4' as NAme
select * from ExampleTable
| Id | Name |
| -------- | -----|
| 1 |Test4 |
GO