什么是自动增量的最佳方法
我正在C#中使用Sql Server 2008 R2构建队列管理系统。一次为多个部门提供服务如客户服务,女士部,注册部。例如。对于什么是自动增量的最佳方法
- 淑女款:令牌{} 1-50
- 客服:令牌{51-350}
- 注册组:标记{351-550}
- 普通客户:令牌{551- 999}
我正在使用这种方法,首先我正在从哪个部门获取请求。在Table中检查该部门的令牌范围,然后获得该部门的令牌的现有值。使用更新下一个数字表格覆盖现有值。
是否有任何其他方法可以使用,因为我面临的问题是有时相同的令牌编号会出现在普通客户/注册/客户/女士区的两个屏幕上。
感谢
你可以使用更新输出语句,就像这样:
use tempdb
go
if object_id('Tokens', 'u') is not null drop table Tokens
if object_id('GetNextToken', 'p') is not null drop procedure GetNextToken
go
create table Tokens (
Id int identity(1,1) not null,
Name varchar(50) not null,
TokenFrom int not null,
TokenTo int not null,
LastUsedToken int null,
constraint PK_Tokens primary key clustered (Id),
constraint UQ_Tokens_Name unique (Name)
)
go
insert into Tokens (Name, TokenFrom, TokenTo)
select 'Ladies Section', 1, 50 union
select 'Customer Care', 51, 350 union
select 'Registration Section', 351, 550 union
select 'Normal Customers', 551, 999
go
create procedure GetNextToken
@name varchar(50),
@token int output
as
begin
declare @tokens table (token int)
update Tokens
set LastUsedToken =
case
when LastUsedToken is null then TokenFrom
when LastUsedToken = TokenTo then TokenFrom
else LastUsedToken + 1
end
output inserted.LastUsedToken into @tokens
where Name = @name
set @token = (select top 1 token from @tokens)
end
go
-- To get 'Ladies Section'
declare @name varchar(50), @token int
set @name = 'Ladies Section'
exec GetNextToken @name, @token output
select @token
go
-- To get 'Customer Care'
declare @name varchar(50), @token int
set @name = 'Customer Care'
exec GetNextToken @name, @token output
select @token
go
-- To get 'Registration Section'
declare @name varchar(50), @token int
set @name = 'Registration Section'
exec GetNextToken @name, @token output
select @token
go
-- To get 'Normal Customers'
declare @name varchar(50), @token int
set @name = 'Normal Customers'
exec GetNextToken @name, @token output
select @token
我也建议你在函数或程序中包装'update'部分 –
@AndreyMorozov同意,我编辑了我的答案 – sventevit
@sventevit,对不起,我在SQL中不太好。您能否让我知道如何获得客户服务,注册和普通客户的下一个令牌? –
我希望大家不要对使用的自动递增列。 –