Whilst locked - see if otherID exists, if so return mainID, if not insert otherID & return new mainID

独自空忆成欢 提交于 2020-01-17 04:43:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!