Identity column is an easiest way to generate sequence unique number in a column of the table. Considering am having a column named "ID" with property as identity with starting value as 1 and it should generate values increased by 1. The syntax is,
id int identity(1,1) -- This column will generate the values 1,2,3,4,....etc...
Now, let's goto our typical problem statement reseeding the identity column.
Problem statement:
Am having five records in the table, the id values 1,2,3,4,5. Now, I am deleting the record 5. After wards am trying to insert another record. Unfortunately we will miss 5 and the record will be inserted with the value 6. How to sort down this issue?
Solution:
SQL server is providing a handy solution to solve this issue. The command is DBCC Checkident. Lets see the syntax for this,
DBCC checkident(tablename, reseed, value to start or reseed the column)
Lets see a small example on this,
First code snippet is to show the problem and the second code snippet is the solution for the problem.
drop table venkatTable
create table venkatTable(id int identity(1,1) primary key, nam varchar(100))
insert into venkatTable values('Venkatesan Prabu')
insert into venkatTable values('Subashini')
insert into venkatTable values('Jayakantham')
insert into venkatTable values('Arunachalam')
insert into venkatTable values('Santhi')
select * from venkatTable
delete venkatTable where id=5
insert into venkatTable values('Santhi')
select * from venkatTable
drop table venkatTable
create table venkatTable(id int identity(1,1) primary key, nam varchar(100))
insert into venkatTable values('Venkatesan Prabu')
insert into venkatTable values('Subashini')
insert into venkatTable values('Jayakantham')
insert into venkatTable values('Arunachalam')
insert into venkatTable values('Santhi')
select * from venkatTable
delete venkatTable where id=5
--Am resetting the id columnwith the maximum value of the column.
declare @val int
select @val=max(id) from venkattable
dbcc checkident (venkatTable,reseed,@val)
insert into venkatTable values('Santhi')
select * from venkatTable
If you dont want to reset the seed value of the column, we can use noreseed option in the abov command,
DBCC checkident(tablename,noreseed)
Thanks and Regards,
Venkatesan Prabu .J
No comments:
Post a Comment