What are the better techniques for inserting a record into a table if it is not there already?
The issue is that the code checks if the record with the criteria exists, and if it does not, it creates one. However, a second thread could come along and check at the same time.
We started experimenting with TABLOCKX which initially worked, although it felt a bit like using an elephant gun, but we are also looking at using snapshot isolation, and it doesn’t work in that context, where the second transaction can just come along and read the table.
This is a common problem, so it seems like there should be a more standard solution. Note that a unique index is not appropriate here, since the fields being searched can contain nulls, and SQL Server 2005 doesn’t support a unique constraint in that context.
I didn’t see anything in the original question about updating the table, so maybe you just want something like: