Question

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?

Was it helpful?

Solution

you can use

insert into ... on duplicate key

look on example @thummper answer:

On duplicate key ignore?

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top