I have a requirement to insert a row into a table if a row does not already exist, and I need to do this using a stored procedure. I therefore need to select to check if the row already exists, followed by an insert. What I want to avoid is a race condition where 2 callers of the stored procedure may see that the row doesn't exist and then both try to insert the row.

My first thoughts on solving this would be to lock the table, but unfortunately you cannot issue LOCK TABLE in a stored procedure.

I want to avoid trapping a duplicate key insertion exception at the client (C#).

Any way of locking the table or alternative solutions?

有帮助吗?

解决方案

you can use

insert into ... on duplicate key

look on example @thummper answer:

On duplicate key ignore?

其他提示

Another option is to use

INSERT IGNORE INTO ... 

and as long as you have a unique key that would be violated by this insert happening twice, it won't be done a second time.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top