Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert identity manually?

CREATE TABLE masterTbl ( id INT IDENTITY(1,1) CONSTRAINT pk_id PRIMARY KEY, name VARCHAR(100))  INSERT INTO masterTbl VALUES ('ABC', 'XYZ','PQR') 

Now

Select * FROM masterTbl 

Result:

id  | name --------------------- 1 |  ABC 2 |  XYZ 3 |  PQR  DELETE FROM masterTbl WHERE id=1 

Now

Select * FROM masterTbl 

Result:

id |  name --------------------- 2 |  XYZ 3 |  PQR 

Now I want to run:

INSERT INTO masterTbl (id, name) VALUES (1, 'MNO') 

How is this possible?

like image 607
RAKESH HOLKAR Avatar asked Sep 24 '12 10:09

RAKESH HOLKAR


People also ask

How do I enable identity insert?

Enabling the property “Enable Identity Insert” by checking the checkbox allows the values to be inserted in the identity field. This way, the exact identity values are moved from source database to the destination table.

How do you add an identity to an existing table?

You can't alter the existing columns for identity. You have 2 options, Create a new table with identity & drop the existing table. Create a new column with identity & drop the existing column.


2 Answers

In it's simplest form, you need to temporarily allow the insertion of identity values

SET IDENTITY_INSERT masterTbl ON INSERT INTO masterTbl (id, name) VALUES (1, 'MNO') SET IDENTITY_INSERT masterTbl OFF 
like image 140
freefaller Avatar answered Oct 07 '22 06:10

freefaller


Yes you can set identity fields manually executing

SET IDENTITY_INSERT masterTbl ON 

then insert your data

INSERT INTO masterTbl (id, name) VALUES (1, 'MNO')  ...... 

and remember to call

SET IDENTITY_INSERT masterTbl OFF 

to reenable the correct functionality

like image 30
Steve Avatar answered Oct 07 '22 07:10

Steve