Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
SQL
insert into Student values(12,'jh','hjf',GETDATE())


What I have tried:

Here Am going insert values to a table. It display the error message like.
An explicit value for the identity column in table 'Student' can only be specified when a column list is used and IDENTITY_INSERT is ON.
Posted
Updated 1-Feb-18 2:33am
Comments
Jörgen Andersson 1-Feb-18 4:51am    
Solution 1 is answering your actual question.
But the question we need to ask is: Why do you want to set the ID in the identity column manually?

Solution 1 does not solve your problem, you also need to specify the names of the columns you want to populate with the insert.

For example:
SQL
SET IDENTITY_INSERT #Student on
insert into #Student (id, firstname, surname, joindate) values(5,'jh','hjf',GETDATE())
SET IDENTITY_INSERT #Student off
But as Jörgen Andersson states in his comment to your question - why do you want to insert a specific value for an identity column? It's not good practice.

Good practice is always to list the columns you are going to populate - it saves major reworks if there are changes to the table schema for a start. It also makes it more obvious that you are not going to include the identity column :-) This is better:
SQL
insert into #Student (firstname, surname, joindate) values('jh1','hjf1',GETDATE())
What you may not have noticed is the effect of your override to the identity column. If you query my data after the two updates above I get
5	jh	hjf	2018-02-01
6	jh1	hjf1	2018-02-01
SQL will not fill in that gap you created.
Worse than that, if I accidentally use an id that is already on the table I will not get any warning! This code
SQL
SET IDENTITY_INSERT #Student on
insert into #Student (id, firstname, surname, joindate) values(5,'jh3','hjf3',GETDATE())
SET IDENTITY_INSERT #Student off
results in
5	jh	hjf	2018-02-01
6	jh1	hjf1	2018-02-01
5	jh3	hjf3	2018-02-01
If I have any processing that relies on id being unique, it's going to break. If I don't have any reason to have id as a unique number then why define it as an identity column in the first place?
 
Share this answer
 
try
SET IDENTITY_INSERT Student on
insert into Student values(12,'jh','hjf',GETDATE())
SET IDENTITY_INSERT Student off

Please read these
SET IDENTITY_INSERT (Transact-SQL) | Microsoft Docs[^]
How to turn IDENTITY_INSERT on and off using SQL Server 2008? - Stack Overflow[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900