I'm using a stored procedure in SQL Server to get the next available number for a tenant. Here is the table, that holds the counter information:
CREATE TABLE [NumbersPool]
(
TenantId [varchar](32) NOT NULL,
Counter [bigint] NOT NULL DEFAULT 0
)
And here is the stored procedure:
CREATE PROCEDURE getNextNumber
(@tenantId varchar(32))
AS
BEGIN
SET NOCOUNT ON
DECLARE @Counter AS BIGINT
SELECT @Counter = Counter
FROM NumbersPool WITH (TABLOCK, HOLDLOCK)
WHERE TenantId = @tenantId
IF @Counter IS NULL
BEGIN
SET @Counter = 0
INSERT INTO NumbersPool (TenantId, Counter)
VALUES (@tenantId, @Counter)
END
ELSE
BEGIN
SET @Counter = @Counter + 1
UPDATE NumbersPool
SET Counter = @Counter
WHERE TenantId = @tenantId
END
RETURN @Counter
END
Now the problem. The procedure seems to work fine with multiple concurrent calls (is called in a transaction with serializable isolation level), but at some point the counter jumps from e.g. 1992 to 25276 without any obvious reason.
Does anybody see any issues in it?