Author: Tomas Rutkauskas
Using InterBase generators for AutoIncrement fields
InterBase doesn't offer the convenient AutoIncrement datatype as some desktop
database systems (MS-Access, Parados) do. In a project I simulated this for a
unique index field by using a trigger combined with a generator.
The example below assumes that there is a table CUSTOMER with a uniquely indexed
The generators' name is GEN_CUSTOMER.
The traditional technique would be to detect the current maximum number max and
then insert a value of [max+1]:
SELECT MAX(cust_hash) + 1 FROM customer
INSERT INTO customer(...)values(...)
The risk with this approach is that a parallel user could theoretically do the same
thing before you write the determined value and end the transaction. The parallel
user would try to post the same number and either cause a unique-index violation or
post a duplicated value!
The trick with the generator is also faster since you don't have to do the max()
query for each insert.
1 2 CREATE GENERATOR gen_customer;
3 4 set GENERATOR gen_customer to 100;
5 6 CREATE TRIGGER customer_autoinc for customer
7 BEFORE INSERT as8 begin9 if (NEW.cust_hash is NULL) then10 NEW.cust_hash = GEN_ID(gen_customer, 1);