1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
|
drop procedure getNext;
drop table compteur;
create table compteur
(
cpt_id int identity(1, 1) not null primary key,
cpt_code varchar(5) not null,
cpt_minimum int not null,
cpt_maximum int not null,
cpt_increment int not null,
cpt_boucle bit not null,
cpt_valeur int not null
);
create unique index uix_compteur_code on compteur(cpt_code);
insert into compteur (cpt_code, cpt_minimum, cpt_maximum, cpt_increment, cpt_boucle, cpt_valeur) values ('CDE', 1, 3, 1, 0, 0);
go
create procedure getNext
@code as varchar(6),
@next as int output
as
declare @id int;
declare @min int;
declare @max int;
declare @inc int;
declare @boucle bit;
declare @val int;
select @next = null;
begin transaction lock;
select @id = cpt_id, @min = cpt_minimum, @max = cpt_maximum, @inc = cpt_increment, @boucle = cpt_boucle, @val = cpt_valeur
from compteur with (holdlock, rowlock)
where cpt_code = @code;
if @id is null
begin
rollback transaction lock;
raiserror('Le compteur %s n''existe pas !', 10, 1, @code);
return;
end;
if @val = @max
begin
if @boucle = 0
begin
rollback transaction lock;
raiserror('Dépassement de l''index du compteur %s', 10, 1, @code);
return;
end;
else
begin
select @next = @min;
end;
end;
else
begin
select @next = @val + @inc;
end;
update compteur
set cpt_valeur = @next
where cpt_id = @id;
commit transaction lock;
go
begin
declare @cpt int;
exec getNext 'CDE', @cpt output;
print 'Compteur CDE = ' + cast(@cpt as varchar);
exec getNext 'CDE', @cpt output;
print 'Compteur CDE = ' + cast(@cpt as varchar);
exec getNext 'CDE', @cpt output;
print 'Compteur CDE = ' + cast(@cpt as varchar);
exec getNext 'CDE', @cpt output;
print 'Compteur CDE = ' + cast(@cpt as varchar);
end;
/*
select *
from compteur;
*/ |