محمدخرم شھزاد محمدخرم شھزاد - 2 months ago 6
C# Question

What is Best Approach for Auto Increament

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

Answer

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
Comments