I have some file processing functionality which uses a database table to establish whether or not a file has been processed.
IF EXISTS (SELECT * FROM FileTable WITH (UPDLOCK, ROWLOCK, HOLDLOCK)
WHERE FileName = @FileToProcess)
BEGIN
-- File already processed.
END
ELSE
BEGIN
-- Process file.
END
The behaviour I want is as follows: -
- Only one transaction should process a file at a time.
- Different files are processed concurrently.
- If an attempt to process the same file is made whilst it is being processed then that transaction will block until the other one finishes.
I am pretty sure this is possible but my SQL locking knowledge is not quite up to scratch! My attempts so far either include the locking hints in the example above, which fails bullet point 2. All other locking hints I have tried have resulted in bullet point 3 failing.
What am I missing?