How to insert values into an Identity column in SQL Server

If the column is defined as identity then SQL Server will automatically insert the values in to identity column whenever new records get inserted. In some situation we may need to insert values into the identity column explicitly. In the following section I have demonstrated how we can achieve this. For demonstration purpose let’s create two tables with identity column and populate with some records.

CREATE TABLE TBLIDENTITY (IID INT IDENTITY (1, 1), ENAME VARCHAR (20) DEFAULT 't-s-q-l.BlogSpot')

INSERT INTO TBLIDENTITY DEFAULT VALUES
INSERT INTO TBLIDENTITY DEFAULT VALUES
INSERT INTO TBLIDENTITY DEFAULT VALUES

CREATE TABLE TBLIDENTITY_TEMP (IID INT IDENTITY (4, 1), ENAME VARCHAR (10) DEFAULT 't-s-q-l')

INSERT INTO TBLIDENTITY_TEMP DEFAULT VALUES
INSERT INTO TBLIDENTITY_TEMP DEFAULT VALUES
INSERT INTO TBLIDENTITY_TEMP DEFAULT VALUES

let’s assume, we want to insert the records from the table TBLIDENTITY_TEMP to TBLIDENTITY whilst we need to preserve the IID column value of TBLIDENTITY_TEMP in TBLIDENTITY. In order to do this, we have to set IDENTITY_INSERT ON.

SET IDENTITY_INSERT TBLIDENTITY ON
INSERT INTO TBLIDENTITY (IID, ENAME)
SELECT * FROM TBLIDENTITY_TEMP
SET IDENTITY_INSERT TBLIDENTITY OFF

1 comment: