I have an arbitrary stored procedure usp_DoubleCheckLockInsert
that does an INSERT
for multiple clients and I want to give the stored procedure exclusive access to writing to a table SomeTable
when it is within the critical section Begin lock
and End lock
.
CREATE PROCEDURE usp_DoubleCheckLockInsert
@Id INT
,@SomeValue INT
AS
BEGIN
IF (EXISTS(SELECT 1 FROM SomeTable WHERE Id = @Id AND SomeValue = @SomeValue)) RETURN
BEGIN TRAN
--Begin lock
IF (EXISTS(SELECT 1 FROM SomeTable WHERE Id = @Id AND SomeValue = @SomeValue)) ROLLBACK
INSERT INTO SomeTable(Id, SomeValue)
VALUES(@Id,@SomeValue);
--End lock
COMMIT
END
I have seen how Isolation Level relates to updates, but is there a way to implement locking in the critical section, give the transaction the writing lock, or does TSQL not work this way?
Obtain Update Table Lock at start of Stored Procedure in SQL Server