I am writing a T-SQL stored procedure that conditionally adds a record to a table only if the number of similar records is below a certain threshold, 10 in the example below. The problem is that this will be launched from a web application, so it will run on multiple threads, and I need to make sure that the table never contains more than 10 similar entries.
The main point of the procedure:
BEGIN
DECLARE @c INT
SELECT @c = count(*)
FROM foo
WHERE bar = @a_param
IF @c < 10 THEN
INSERT INTO foo
(bar)
VALUES (@a_param)
END IF
END
I think I could solve any potential concurrency problems by replacing the select statement:
SELECT @c = count(*) WITH (TABLOCKX, HOLDLOCK)
But I'm curious if there are any methods, other than locking, for managing concurrency problems in T-SQL