18

What is the scope of SET IDENTITY_INSERT xyz ON?

If I use this in one stored procedure for a certain table, what happens if a different user running a different procedure, inserts into that certain table at the same time?

Also, what happens if different users/procedures try to set SET IDENTITY_INSERT xyz ON for different tables at the same time?

2
  • I would be very wary of doing this no matter what. Set_identity insert on is only supposed to be done rarely and for the occasional import of data being moved from another system that must retain it's identity usually only when you first intialize the system. It is a very poor practice to use this in an application. What if two users want to insert the same value for differnt records. There is areason why identities are autogenerated and they should remain this way or you should not be using them. Commented Apr 26, 2011 at 14:59
  • 1
    @HLGEM, this is part of a restore feature, where deleted data is added back (copied from a historical log table) Commented Apr 28, 2011 at 12:52

2 Answers 2

19

It's a session option a table can only have the option on for any one table at a time but multiple different sessions can have it on for the same table (not sure that would ever be a good idea though!)

When a child batch finishes (that sets this option) it looks like it automatically gets unset for the connection.

CREATE TABLE Tst (C INT IDENTITY(1,1)) EXEC('SET IDENTITY_INSERT Tst ON') INSERT INTO Tst(C) VALUES (1) /*Fails - Complains IDENTITY_INSERT is off*/ SET IDENTITY_INSERT Tst ON EXEC('INSERT INTO Tst(C) VALUES (1)') /*Succeeds this way round*/ SET IDENTITY_INSERT Tst OFF SET IDENTITY_INSERT Tst ON EXEC('SET IDENTITY_INSERT Tst ON; INSERT INTO Tst(C) VALUES (1);') /* Also succeeds like this*/ 
Sign up to request clarification or add additional context in comments.

1 Comment

@RacerX - Yes but see my comment about it being reset as you go up the call stack.
3

My testing (SQL 2008 R2) shows that the identity spec on a column still hands out the right values in one session, even if the table has IDENTITY_INSERT ON in another session.

You should be able to bulk insert data into the table with specific identity column values in one session (with IDENTITY_INSERT ON) while another user (in another session) is depending on the identity column to function normally.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.