SQL Server 2008: I’ve got a situation here in which I wish to read from a table and write a row under certain conditions. The problem is that I don’t want another request coming it at exactly the same time and doing the same thing. I’ll try to explain here:
Table Name: RequestQueue
Columns:
RequestID, StartDate, EndDate, RequestResult
Sample Data
1, 12/4/10 1:00pm, 12/4/10 1:02pm, Success
2, 12/4/10 1:04pm, 12/4/10 1:05pm, Success
3, 12/4/10 1:00pm, NULL, NULL
When a page loads in my app, I want it to look at this table and if there is a request still pending like (ID #3) it will not do anything. Otherwise, if there are no requests pending, it creates a new row with the ID and StartDate filled in.
The issue is that we could get into a situation where the page is loaded twice at almost exactly the same time. If they happen to both read from the table before the new row is produced, then I could get two new rows in there. I want to have some sort of query that reads from the table and if there are no requests pending, inserts the new row with the StartDate filled in. I want that query to run all the way before another page can even read from this table so I don’t get the “double row” effect.
I might need “locking” or something, I googled that but haven’t found something for my exact situation. I’m sure this could be a simple stored procedure I just need a push in the right direction here.
Thanks,
Robert
Assuming that you just want to block all concurrent access to the table you could just do.
Alternatively you could just serialise access to the
SELECT/INSERTcode inside the specific procedure without taking an exclusive table lock by using sp_getapplock