Home > DeveloperSection > Forums > How to insert data in Identity Column?
Alex R
Alex R

Total Post:40

Points:280
Posted on    November-12-2010 8:46 AM

 MSSQL Server MSSQL Server 
Ratings:


 2 Reply(s)
 2885  View(s)
Rate this:

Hi,
I want to insert record in database and I am able to insert using insert query, but the problem is that I am unable to insert data in Identity column.

Here is the Query which I am writing

INSERT into tblLogin ([ID], [FirstName], [LastName], [Password) VALUES (15, N'abc', N'xyz', N'pass')

 

Please tell me what is wrong in the query?

Thanks in advance.



Amit Singh

Total Post:103

Points:721
Posted on    November-12-2010 9:01 AM

Hi Haider,

Your query is correct, but the problem is that you can not insert data directly into Identity column.

All you have to do is to set Identity insert of that column on, and after you are done just set it off.

Here is the script that will do what you want.

SET IDENTITY_INSERT tblLogin ON

INSERT into tblLogin ([ID], [FirstName], [LastName], [Password]) VALUES (15, N'abc', N'xyz', N'pass')

SET IDENTITY_INSERT tblLogin OFF

Hope this will help you.


Shankar M

Total Post:25

Points:175
Posted on    February-10-2013 9:12 PM

Hi Rizvi,

There is no problem with the query, The problem is that you cannot insert into a column that is defined as Identity column in SQL
Server.

Instead, you have to Modify the column Property  Identity Specification - (Is Identity) to No. Then, your statement will work fine.

To insert into a table EMP with Identity column where its Is Identity Property set to Yes can be done as shown.

CREATE TABLE EMPLOYEE(EID INT IDENTITY(1,1),
ENAME VARCHAR(20));

INSERT INTO EMPLOYEE(ENAME)VALUES('SAM');

Here, the Identity value is managed the SQL Server and we don't need to specify
the column while writing your Insert Statement.

Regards,
Shankar


Modified On Feb-10-2013 09:14:48 PM

Don't want to miss updates? Please click the below button!

Follow MindStick