I need to run a SQL Server query that either "gets" or "creates" a record. Pretty simple, but I am not sure if this will create any race conditions.
I have read a few articles regarding locking during insert/updates e.g. http://weblogs.sqlteam.com/dang/archive/2007/10/28/Conditional-INSERTUPDATE-Race-Condition.aspx, but I'm not sure if this is relevant to me given I'm using SQL Server 2012, and I don't have contention over modification per se, only over ensuring 'one off creation' of my record.
Also, I will have a primary key constraint over the Id
column (not an identity column), so I know the race condition at worst could only ever create an error, and not invalid data, but I also don't want the command to throw an error.
Can someone please shed some light on how I need to solve this? Or am I over thinking this and can I simply do something like:
IF EXISTS(SELECT * FROM Table WHERE Id = @Id)
BEGIN
SELECT Id, X, Y, Z FROM Table WHERE Id = @Id
END
ELSE
BEGIN
INSERT INTO Table (Id, X, Y, Z)
VALUES (@Id, @X, @Y, @Z);
SELECT @Id, @x, @Y, @Z;
END
I've been in document database land for a few years and my SQL is very rusty.