I suspect your issue is unrelated to your use of MERGE
or HOLDLOCK
. I see no reason to introduce cumbersome MERGE
syntax here, since it provides no benefit, and especially given the potential issues it can cause in other areas. I suggest a very simple INSERT ... WHERE NOT EXISTS
:
INSERT dbo.Test(Id, FailedAttempts, DateCreated)
SELECT @GameId, 0, SYSDATETIME()
WHERE NOT EXISTS
(
SELECT 1 FROM dbo.Test WITH (HOLDLOCK)
WHERE Id = @GameId
);
I'd prefer this over just blindly trying to insert and getting a PK violation for the reasons outlined here and here - in almost all cases, forcing SQL Server to try and get an exception instead of checking yourself first will yield worse performance.