Reputation: 384
I have created a stored procedure that is supposed to return a unique number by incrementing a value in a table every time it is called.
ALTER PROCEDURE [dbo].[GetNextNumber] @Next_Number char(9) output AS
BEGIN
BEGIN TRAN
DECLARE @Current_Number int
SET @Current_Number = (SELECT CONVERT(int, Counter) FROM CounterTable)
IF(@Current_Number IS NULL)
BEGIN
SET @Next_Number = '000000000'
INSERT INTO CounterTable (Counter) VALUES (@Next_Number)
END
ELSE IF(@Current_Number >= 999999999)
BEGIN
SET @Next_Number = '000000000'
UPDATE dbo.CounterTable SET Counter = @Next_Number
END
ELSE
BEGIN
SET @Next_Number = REPLACE(STR(@Current_Number + 1, 9),' ', '0')
UPDATE dbo.CounterTable SET Counter = @Next_Number
END
COMMIT TRAN
END
Sometimes the stored procedure returns the same number twice. What have I done wrong?
Upvotes: 4
Views: 442
Reputation: 239654
I've done this before:
update CounterTable set @Next_Number = Counter = Counter + 1
which keeps it in a single statement, and so (unless you switch to Read Uncommitted, possibly) shouldn't have issues with multiple callers.
Upvotes: 3
Reputation: 58431
You could explicitly lock the Countertable
using Table Hints
...
SET @Current_Number = (
SELECT CONVERT(int, Counter)
FROM CounterTable WITH(Holdlock, Updlock)
)
...
Upvotes: 2