[Short]
I have the following situation: user A
attempts to insert data DA
into the database. To check whether user A
is allowed to insert DA
, I need to run a query and do some computation. The problem I'm running into is that while I do the computation, another user (B
) also attempts to insert data into the database. Now, suppose both users read the information needed for the computation before new data is inserted, then they might both get cleared for insertion whilst data from user A
would forbid user B
from inserting, thus leaving the database in a inconsistent state.
How can I solve this kind of concurrency in Azure SQL Database V12?
[Detailed]
The data the user is inserting is the beginning and end of a time interval, such as start: 6:00, end: 7:00
.
The requirement is that there must be no time interval overlaps. This means that intervals start: 6:00, end: 9:00
and start: 5:00, end: 6:00
can't both exist.
Currently what I'm doing is checking whether there are any rows that overlap the new interval the user is trying to insert using the following query:
SELECT COUNT(*) FROM [Table1] WHERE Start <= attempEnd && End >= attemptStart
Now, the problem is that multiple users might be trying to insert an interval and these new intervals might overlap each other. However, this information might not be available at the time the query above runs, which causes overlapping intervals being inserted.
How can I solve this kind of concurrency in Azure SQL Database V12?