title: c# - concurrent inserts with Scope_Identitiy()
body: <p>We have a dozen clients which use an Assembly for inserting data into my SQL Server 2012 in form of simple SQL statements.</p>
  
  <p>There are two tables (e.g. <code>[User]</code> and <code>[Location]</code>) with an identity column and a foreign key.</p>
  
  <p>The execution of the statement is always the same: create user, save the new id as foreign key for creating the location. </p>
  
  <p>In pseudo code:</p>
  
  <pre><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();
  </code></pre>
  
  <p>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 <code>SCOPE_IDENTITY()</code> retrieves the new created ID of an <code>User</code> created by another client/thread?</p>
  
  <p>Especially is there time between the insert of the user and <code>Scope_Identity()</code> for another thread to insert a new user which <code>Scope_Identity</code> reads?</p>
  
  <p>Is maybe the <code>OUTPUT</code> clause an alternative?</p>