Inserting values into an identity column

Posted By  Mohammad Shahanshah Ansari On 18 Jun 2010 11:06:09
emailbookmarkadd commentsprint
No of Views:729
Bookmarked:0 times
Votes:0 times

Introduction

The identity column gets value assigned automatically when a new records inserted into the table.Its possible to insert a value into an identity column by setting the IDENTITY_INSERT to ON.

Lets look at the following example,

--Test table with an identity columnCREATE TABLE #IDENTESTTABLE 
(ROWNO_COL INT IDENTITY(1,1),VALUE_COL VARCHAR(15))GO--Inserting a row into the tableINSERT #IDENTESTTABLE(ROWNO_COL, VALUE_COL) VALUES (1, 'TEST VALUE')The above insert statement would terminate with the following error,Msg 544, Level 16, State 1, Line 1Cannot insert explicit value for identity column in table '#IdenTestTable____000000000004' 
when IDENTITY_INSERT is set to OFF.

To avoid this error set IDENTITY_INSERT to ON.Here we go,

SET IDENTITY_INSERT #IDENTESTTABLE ONINSERT #IDENTESTTABLE(ROWNO_COL, VALUE_COL) 
VALUES (1, 'FIRST ROW')SET IDENTITY_INSERT #IDENTESTTABLE OFF.

 More fun with IDENTITY here. Enjoy the code snippet.

Sign Up to vote for this article
Other popular Tips/Tricks
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top