问题
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.
回答1:
We can do a conditional INSERT, followed by a plain SELECT:
DECLARE @OtherID int
INSERT INTO TableA (OtherID)
SELECT @OtherID
WHERE NOT EXIST (SELECT * from TableA where OtherID = @OtherID)
SELECT MainID from TableA where OtherID = @OtherID
来源:https://stackoverflow.com/questions/43805829/whilst-locked-see-if-otherid-exists-if-so-return-mainid-if-not-insert-otheri