Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the scope of SET IDENTITY_INSERT xyz ON?

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?

like image 445
RacerX Avatar asked Apr 26 '11 14:04

RacerX


People also ask

What is Identity_insert is set to ON?

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value. The setting of SET IDENTITY_INSERT is set at execute or run time and not at parse time.

What is Identity_insert on off in SQL Server?

The set identity_insert command in SQL Server, as the name implies, allows the user to insert explicit values into the identity column of a table.

What is the use of Identity_insert?

IDENTITY_INSERT is a table property that allows you to insert explicit values into the column of table identifiers, i.e. into the column with IDENTITY. The value of the inserted identifier can be either less than the current value or more, for example, to skip a certain interval of values.

What is the use of Scope_identity () function?

The SCOPE_IDENTITY() function returns the null value if the function is invoked before any INSERT statements into an identity column occur in the scope. Failed statements and transactions can change the current identity for a table and create gaps in the identity column values.


2 Answers

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*/
like image 156
Martin Smith Avatar answered Sep 23 '22 21:09

Martin Smith


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.

like image 24
user1302071 Avatar answered Sep 25 '22 21:09

user1302071