Surprisingly can’t find a match for my question. I have one table that I need to use a source of data to insert to another and then delete whatever has been inserted. This has to be accomplished in blocking manner, i.e. if the same query/SP is executed at the same time, the same records must not be moved thus creating duplicates.
I have a feeling it’s something relatively simple but I am not sure I totally understand how locking works in SQL. It appears super trivial in C# (just a monitor) but SQL…
As an example, you may consider producer-consumer model, i.e. some sort of a table that serves as a queue, some threads insert into it some consume. Insertion apparently is not a problem, but consumption is what I am wondering about.
UPDATE:
Two good candidate solutions for me:
- use SELECT FOR UPDATE (need to figure out for how long row locks are
hold) - use a field to mark records before manipulating on them
And still need to figure out that SERIALIZABLE IL thing…
Thank you everyone who took an effort and replied – this community is so great.
some suggestions…
make sure your tables have proper keys or unique contraints such that duplicates can not be inserted
I would use a stored procedure to do the bulk move (insert + delete) within a begin/commit transaction. I would also make sure the rows that are selected to move is done so with row level locking. (This could however have a performance impact if these tables have a lot of select requests).
alternatively, you could actually lock on the C# code that invokes this action, blocking to make sure that no to user can enter the invoke the method at the same time.