if exists (select 1 from schema.TableName (nolock) where Id = @id)
update schema.TableName set DocumentXML = @documentXml, ClientDocumentGUID=@clientDocGuid, Incomplete = @incomplete where Id = @id
else
insert into schema.TableName
select @id, @templateId, @clientVisitGuid, @clientGuid, @chartGuid, @scmDocumentGuid, @clientDocGuid, @incomplete, getdate(), @createdByGuid, @documentXml
I have a C# program that runs the query above. I have situations coming up where rows are being inserted twice. I think the issue is this query. The idea is that the query can be run twice given the same @Id. The first time should be an insert, the second time should be an update.
Note the query has a (no lock). Does this mean that the queries are not necessarily run in a FIFO fashion? I believe the two row problem can only arise if I run this query asynchronously.
If you have two requests processing at the same time they will both insert since your ignoring all locks on the first table. I like using merge in these cases. Or remove your no lock and ensure your transaction isolation level is snapshot or serialized.