Let's assume the following simple table in SQL Server 2012:
CREATE TABLE Person (
Id INT IDENTITY(1, 1) PRIMARY KEY,
Name NVARCHAR(50)
)
And the following corresponding class in C#:
public class Person
{
public int Id {get; set;}
public string Name {get; set;}
}
Consider now the following CreatePerson
method (pseudo code):
public static Person CreatePerson(string name) {
...
DB.Execute("INSERT INTO Person(Name) VALUES (name)", name);
int lastId = DB.Get("SELECT MAX(Id) FROM Person");
return new Person {Id = lastId, Name=name};
}
This method creates a new person row in the db, builds a new Person object and then it returns the created object that is supposed to contain the database generated Id.
Is it safe and/or correct (from a concurrency perspective) to get the last generated Id by using the following SELECT statement?
SELECT MAX(Id) FROM Person
I am concerned about the following scenario:
- USER A Inserts a
person 1
- USER B Inserts a
person 2
- USER A reads the last Id and thinks that it is the Id of
person 1
Note that USER A and USER B here refers to threads handling the two separate queries to the database.