There is lots of information in the internet regarding this common \"problem\".
Solutions like:
IF NOT EXISTS() BEGIN INSERT INTO (...) END
<
To answer the updated question repeatable read
would still not be sufficient.
It is holdlock
/ serializable
level that you would need.
You are trying to prevent phantoms (where on the first read no rows met the criteria so the NOT EXISTS
returns true but subsequently a concurrent transaction inserts a row meeting it)
With TRY/CATCH you can avoid the extra read
BEGIN TRY
INSERT etc
END TRY
BEGIN CATCH
IF ERROR_NUMBER() <> 2627
RAISERROR etc
END CATCH
If you can discard duplicates, this is a highly scalable technique
Links: