Wednesday, March 9, 2011

How to reset identity on SQL Server




When we create temporary table that contain row number on that table, we can create it by using int IDENTITY(1,1) – for iteration 1 step, here the scripts that we use :



drop table #tempTable

create table #tempTable
(  id int identity(1,1)
  ,name varchar(50)
  )

insert #tempTable
select 'John'

insert #tempTable
select 'Light'

insert #tempTable
select 'Lus'

delete #tempTable

insert #tempTable
select 'JJ'

insert #tempTable
select 'BB'

delete #tempTable
-- reset identity value on table
--DBCC CHECKIDENT (#tempTable, RESEED, 0)


insert #tempTable
select 'AA'

insert #tempTable
select 'DD'


select * from #tempTable


And the result like this :

image





If we use keyword : DBCC CHECKIDENT we can handle reset identity column value in SQL Server, here the script that we tried:



drop table #tempTable

create table #tempTable
(  id int identity(1,1)
  ,name varchar(50)
  )

insert #tempTable
select 'John'

insert #tempTable
select 'Light'

insert #tempTable
select 'Lus'

delete #tempTable

insert #tempTable
select 'JJ'

insert #tempTable
select 'BB'

delete #tempTable
-- reset identity value on table
DBCC CHECKIDENT (#tempTable, RESEED, 0)


insert #tempTable
select 'AA'

insert #tempTable
select 'DD'


select * from #tempTable
-- check identity lastposition
DBCC CHECKIDENT (#tempTable)


And the result will be right this :




image


Hope this information will help us to know SQL Server more.











No comments:

Hukum Tabur Tuai

Ingatlah hukum dasar ini, dalam kehidupanmu  Barang siapa yang menanam, dia pula yang akan menuai