I have a DocumentJob table that contains jobs to be performed against a given document. Each row in the table has jobId, documentId and jobstatus.
Multiple threads / processes would be attempting to add to this table at any given time (using the code given below)
begin tran
if exists
(
select 1 from DocumentJob
where DocumentId = @inDocumentId
and Status in ('Running', 'New')
)
throw 50001, 'New or Active Job for Document is already present', 1
insert into DocumentJob (DocumentId, Status) values(DocumentId, 'New')
select @JobId = scope_identity();
commit;
For a given document Id - I would like to add a new job only if there is no other job for the document that is either running or new. Does the following code snippet take care of the above requirement or would there be some conditions where the above condition can be violated?
My objective is to understand if the table would be properly locked etc. when the above proc is called simultaneously.