Subject Re: [firebird-support] Unique keys without gaps
Author Elmar Haneke
> I have a question: How can I get straight numbers without gaps safely? I
> thought about a table, where I can store the actual value, and a field which
> can be set if anybody gets the value, and increments by one. Then unsets
> that field. When somebody tries to get a value, it first checks if that
> 'semaphore' is set.

By using firebirds internal locking you can make it more simple:

Create an Table for any number of counters:

CREATE TABLE Counters(
CounterId int,
CounterVal int
);

Each Counter you need does correspond to an single row in that table:

To allocate an new Number execute:

UPDATE Counters
SET CounterVal=CounterVal+1
WHERE CounterId=?

Afterwards you can read the new value by

SELECT CounterVal
FROM Counters
WHERE CounterId=?

The Values are in sequence since the Update statement is blocked while
an uncommitted transaction has changed the "CounterVal".

The Problem of this solution is that there is an Bottleneck in the
locking and deadlocks might occur. Therefore this is not an general
replacement for Generators but you can use it for Generation of
accounting numbers.

Elmar