我在MS-Sqlserver 2008上使用存储过程,它生成一个渐进的字母数字序列,用于在另一个表中存储不同数据的负载。
但是现在,当多个进程几乎同时访问此存储过程时,通常会出现问题。
有没有人有建议,如何建立或如何解决这些问题?
以下是SP的实际代码:
CREATE PROCEDURE [dbo].[GetNextAlpha] @s varchar(8) OUTPUT
AS
BEGIN TRANSACTION
DECLARE @res INT;
EXEC @res = sp_getapplock
@Resource = 'Upsert_app_lock',
@LockMode = 'Exclusive',
@LockOwner = 'Transaction',
@LockTimeout = 2000,
@DbPrincipal = 'public';
IF @res NOT IN (0, 1)
BEGIN
RAISERROR ( 'Unable to acquire Lock', 16, 1 )
END
ELSE
BEGIN
DECLARE @n CHAR(36) = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
DECLARE @pos TINYINT;
SET @s = (SELECT TOP 1 [CurHighKey] FROM [dbo].[HighKey]);
SET @pos = LEN(@s);
WHILE @pos > 0
BEGIN
IF SUBSTRING(@s, @pos, 1) = 'Z'
BEGIN
SET @s = STUFF(@s, @pos, 1, '0');
SET @pos = @pos - 1;
END
ELSE
BEGIN
SET @s = STUFF(@s, @pos, 1, SUBSTRING(@n, CHARINDEX(SUBSTRING(@s, @pos, 1), @n) + 1, 1))
SET @pos = 0
END
END
UPDATE [dbo].[HighKey] set [CurHighKey] = @s;
EXEC @res = sp_releaseapplock
@Resource = 'Upsert_app_lock',
@DbPrincipal = 'public',
@LockOwner = 'Transaction';
END
COMMIT