Thursday 11 July 2013

How to insert data in identity column in Sql Server


What is Identity Clause

If user want  to  added will automatically any colume use idendity clause
The identity clause specifies that the column RollNo is going to be an identity column. The first record added will automatically be assigned a value of 1 (the seed) and each subsequent record will be assigned a value 1 higher (the increment) than the previous inserted row. Most identity columns I see are specified as IDENTITY(1,1) but I used IDENTITY(1000,5) so the difference would be clear ..




--create  table StudentRecord with identity colume with SrNo............................

create  table StudentRecord(SrNo int identity(1,1) primary key,Name nvarchar(50),Course nvarchar(50))


--create  table StudentRecord with identity colume with SrNo with Sql Server Wizard….




insert  record  in table….
insert into StudentRecord values('Kush Tiwari','M C A')

when insert  record  in table with identity colume

insert into StudentRecord values(2,'Dinesh Yadav','B.Tech.')

Show this type  error………………

Msg 8101, Level 16, State 1, Line 1
An explicit value for the identity column in table 'StudentRecord' can only be specified when a column list is used and IDENTITY_INSERT is ON.

If you want to  insert  record  in table with identity colume  first  on identity_insert..

set identity_insert studentrecord on

insert into StudentRecord (SrNo,Name,Course)values(6,'Dinesh Yadav','B.Tech.')
insert into StudentRecord (SrNo,Name,Course)values(7,'Kanema','B.Com.')


set identity_insert StudentRecord off


If you have deleted all the rows from table and you want to reset the identity columns value  use (DataBase Consistency Checker) DBCC CHECKIDENT command


 For example

DBCC CHECKIDENT('StudentRecord',RESEED,0)

0 comments:

Post a Comment