2016-10-03 31 views
1

我正在C#中使用Sql Server 2008 R2構建隊列管理系統。一次爲多個部門提供服務如客戶服務,女士部,註冊部。例如。對於什麼是自動增量的最佳方法

  • 淑女款:令牌{} 1-50
  • 客服:令牌{51-350}
  • 註冊組:標記{351-550}
  • 普通客戶:令牌{551- 999}

我正在使用這種方法,首先我正在從哪個部門獲取請求。在Table中檢查該部門的令牌範圍,然後獲得該部門的令牌的現有值。使用更新下一個數字表格覆蓋現有值。

是否有任何其他方法可以使用,因爲我面臨的問題是有時相同的令牌編號會出現在普通客戶/註冊/客戶/女士區的兩個屏幕上。

感謝

+3

我希望大家不要對使用的自動遞增列。 –

回答

1

你可以使用更新輸出語句,就像這樣:

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 
+0

我也建議你在函數或程序中包裝'update'部分 –

+0

@AndreyMorozov同意,我編輯了我的答案 – sventevit

+0

@sventevit,對不起,我在SQL中不太好。您能否讓我知道如何獲得客戶服務,註冊和普通客戶的下一個令牌? –

相關問題