12

Possible Duplicate:
Cannot insert explicit value for identity column in table ‘table’ when IDENTITY_INSERT is set to OFF

I am new to SQL. I am trying to write a INSERT query in SQL server 2008 Express edition.

The query is :

insert into customers
values(201, 'Singh', 'rajnish', '101 bhandup', 'mumbai', 'mp', 33321, 0, null, 123.89, 25.00)

But I am getting following error.

An explicit value for the identity column in table 'customers' can only be specified when a column list is used and IDENTITY_INSERT is ON.

I searched stackoverflow. Found some similar type of questions but unable to understand the explanation. Kindly help me to understand the error and rectify it.

EDIT :

I tried to do :

SET IDENTITY_INSERT customers ON;
insert into customers
values(201, 'Singh', 'rajnish', '101 bhandup', 'mumbai', 'mp', 33321, 0, null, 123.89, 25.00)
SET IDENTITY_INSERT customers OFF;

but again I am getting the same error.

Community
  • 1
  • 1
user1716251
  • 135
  • 1
  • 1
  • 6

3 Answers3

20

Try this

SET IDENTITY_INSERT customers ON
GO
insert into customers(id, ...)
values(201,'Singh','rajnish','101 bhandup','mumbai','mp',33321,0,null,123.89,25.00)
SET IDENTITY_INSERT customers OFF
Community
  • 1
  • 1
Aleksandr Fedorenko
  • 16,594
  • 6
  • 37
  • 44
4

If your first value is the identity column then just remove it, like this:

insert into customers
values('Singh','rajnish','101 bhandup','mumbai','mp',33321,0,null,123.89,25.00)
Niklas
  • 13,005
  • 23
  • 79
  • 119
2

When a table is using an identity field it chooses it's own values. It tracks these values to make sure that it never tries to enter a duplicate and will produce this error if you try to specify your own.

So, in your case either A insert the row without the field that has been marked as an identity field; letting the sql engine pick it's own value for that field. ( that's the whole reason your using an identity field right )

Or, B. Enable identity_insert on before running your insert ( if you have a good reason for inserting a specific value as the key ).

You also need to use a valid insert statement. Specify the columns you're inserting as well as the values.

RThomas
  • 10,702
  • 2
  • 48
  • 61