October 17, 2013

SQL Server - How to Insert Values into Identity Column


SQL Server - How to Insert Values into Identity Column 

 To insert value in identity column I will explain with one example for that first create one sample table like as shown below


CREATE TABLE TableTemp
 (
 UserId int PRIMARY KEY IDENTITY,
 UserName varchar(120),
  Password varchar(50)
 )
Once we create TableTemp insert data like as shown below

INSERT INTO TableTemp(UserId,UserName,Password) VALUES(1,'Hello','******')
Whenever we run above query we will get error message like as shown below

Msg 544, Level 16, State 1, Line 1
Cannot insert explicit value for identity column in table 'TableTemp' when IDENTITY_INSERT is set to OFF.
Based on above error message we can realize that identity columns won’t allow to insert new values when IDENTITY_INSERT is OFF .To solve this problem we need to set is ON for that we need to write the code like as shown below

SET IDENTITY_INSERT TableTemp ON
INSERT INTO TableTemp(UserId,UserName,Password) VALUES(1,'Hello','*****')
INSERT INTO TableTemp(UserId,UserName,Password) VALUES(2,'Satyam','******')
SET IDENTITY_INSERT TableTemp OFF
Once we run above query our Output will be like this

---------------------------------------
(1 row(s) affected)
(1 row(s) affected)
In this way we can insert values to identity columns in SQL Server.

 

No comments: