Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT record to SQL table with IDENTITY column

Tags:

i have this sql table

CREATE TABLE Notes(
    NoteID [int] IDENTITY(1,1) NOT NULL,
    NoteTitle [nvarchar](255) NULL,
    NoteDescription [nvarchar](4000) NULL
) CONSTRAINT [PK_Notes] PRIMARY KEY CLUSTERED 
(
    NoteID ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
 ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

And i want to copy records from a temporary table INCLUDING the NoteID(using sql query)..

this is my script:

SET IDENTITY_INSERT Notes OFF

INSERT INTO Notes (NoteID, NoteTitle,NoteDescription)
SELECT NoteID, NoteTitle,NoteDescription from Notes_Temp

SET IDENTITY_INSERT Notes ON

with this script, i'm getting an error:

Cannot insert explicit value for identity column in table 'Notes' when IDENTITY_INSERT is set to OFF.

is there other way of insert records to a table with identity column using sql query?

like image 706
Eytch Avatar asked May 27 '13 05:05

Eytch


People also ask

How will you insert data into a table with identity column in SQL Server?

To manually insert a new value into the Id column, we first must set the IDENTITY_INSERT flag ON as follows: SET IDENTITY_INSERT Students ON; To set the IDENTIT_INSERT flag ON we need to use the SET statement followed by the flag name and the name of the table.

Can we insert a row for identity column?

Yes, it is true. But, there is a way that allows us to explicitly insert and not update a value in the identity column. This is a set statement that allows user to inserted a value into the identity column. It allows us to do so when this set statement is on otherwise we cannot insert value to identity column.


2 Answers

Change the OFF and ON around

SET IDENTITY_INSERT Notes ON

INSERT INTO Notes (NoteID, NoteTitle,NoteDescription)
SELECT NoteID, NoteTitle,NoteDescription from Notes_Temp

SET IDENTITY_INSERT Notes OFF
like image 168
Adriaan Stander Avatar answered Nov 01 '22 13:11

Adriaan Stander


SET IDENTITY_INSERT Notes ON

INSERT INTO Notes
/*Note the column list is REQUIRED here, not optional*/
(NoteID, NoteTitle,NoteDescription)
SELECT NoteID, NoteTitle,NoteDescription from Notes_Temp

SET IDENTITY_INSERT Notes OFF

You're inserting values for NoteId that is an identity column. You can turn on identity insert on the table like this so that you can specify your own identity values.

like image 43
Ahmed Avatar answered Nov 01 '22 14:11

Ahmed