I need to check if a unique int - otherID (not the primary key) exists in a table. If it does, return the primary key. If it doesn't, insert a record containing the otherID I checked, then return the new primary key.
ID unqiueidentifier, --PK
name varchar(100),
otherID int --Unique
I need to holdlock whatever statement I use because between checking and inserting a concurrent user could insert the same otherID.
I was looking at using a MERGE with holdlock - but it seems that can only be used for INSERT / UPDATE / DELETE - not for selecting.
I'm using this from Dapper in an ASP.net MVC 5 app.
I would like to do this in a single database roundtrip if possible.
Other than a MERGE I'm not even sure what to search for on Google - I don't know if this is possible?!
I want to avoid the chance of a race condition / unique key violation.