What is Best Approach for Auto Increament

梦想与她 提交于 2020-01-05 06:54:05

问题


I am building a Queue Management System in C# using Sql Server 2008 R2. Providing Services in many departments at a time Like Customer Care, Ladies Section, Registration Section. For Example. For

  • Ladies Section : Token {1-50}
  • Customer Care : Token {51-350}
  • Registration Section : Token {351-550}
  • Normal Customers: Token {551-999}

I am using this Approach, First of all i am looking from which department I am getting request. Check Token Range of this department in Table, then getting existing value of the Token for this department. Overriding existing value with Updating Next Number table.

Is there any other approach i can use because i am facing problem that sometimes same Token Number is coming on Two Screens of Normal Customer's/Registration/Customer/Ladies Sections.

Thanks


回答1:


You could use update with output statement, like this:

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


来源:https://stackoverflow.com/questions/39830614/what-is-best-approach-for-auto-increament

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!