We have a dozen clients which use an Assembly for inserting data into my SQL Server 2012 in form of simple SQL statements.
There are two tables (e.g. [User]
and [Location]
) with an identity column and a foreign key.
The execution of the statement is always the same: create user, save the new id as foreign key for creating the location.
In pseudo code:
//open DB Connection
Connection.Open();
//Insert user
"INSERT INTO User (Name, Birthdate) VALUES ("Smith", "1.1.1919");
SELECT SCOPE_IDENTITY();" //save the new ID in var "newID"
//Execute Statement
ExecuteQuery();
//Insert Location
"INSERT INTO Location(Country, City, User_ID) VALUES ("Germany", "Cologne", newID)"
//Execute Statement
ExecuteQuery();
//close Connection
Connection.Close();
No magic till this point...but if I run this code at the same time on multiple clients or in parallel threads is there a possibility that SCOPE_IDENTITY()
retrieves the new created ID of an User
created by another client/thread?
Especially is there time between the insert of the user and Scope_Identity()
for another thread to insert a new user which Scope_Identity
reads?
Is maybe the OUTPUT
clause an alternative?