I've got a small table containing user settings like window position, just a simple name=value pair table where the name needs to be unique:
CREATE TABLE dbo.[Settings]
(
[Name] [nvarchar](100) NOT NULL,
[Value] [nvarchar](4000) NOT NULL,
CONSTRAINT [PK_Settings] PRIMARY KEY CLUSTERED
(
[Name] ASC
) ON [PRIMARY]
) ON [PRIMARY]
When I store a changed setting, I start a transaction, try to update the value, if the update fails (because the record does not exist yet) I insert a new record:
// Begin Transaction
cmd.CommandText = "UPDATE dbo.[Settings] SET [Value] = @value WHERE [Name] = @name";
cmd.Parameters.AddWithValue("@value", value);
cmd.Parameters.AddWithValue("@name", name);
int cmdrc = cmd.ExecuteNonQuery();
if (cmdrc != 1)
{
cmd.CommandText = "INSERT INTO dbo.[Settings] ([Name], [Value]) VALUES (@name, @value)";
cmd.ExecuteNonQuery();
}
// Commit Transaction
My problem: if two threads happen to try and store a value for the same name at the same time (which does happen very rarely, but still), there will be a conflict:
Both threads try and update, both threads get cmdrc==0, both threads try and insert the new value, only one will succeed, the other one will get a SqlException.
I thought the transaction would lock the record, but it seems, since there is no record found on the Update statement, it does not get locked, so the other thread trying to update the same 'name' value will not be blocked, race condition happens.
Is there a way to get SQL Server to lock the keyword even though there is no record found for it?