sql >> Database teknologi >  >> RDS >> Sqlserver

Hvad er den bedste tilgang til automatisk stigning

Du kan bruge opdatering med output-sætning, som denne:

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



  1. Tilføjelse af fremmed nøgle mislykkes i MySQL med fejlkode 1005, nummer 150

  2. mysqldump virker ikke i cron

  3. Sådan får du database-metadata

  4. Kodedækning for PL/SQL