Mirror

Using InterBase generators for AutoIncrement fields (Views: 100)


Problem/Question/Abstract:

Using InterBase generators for AutoIncrement fields

Answer:

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 field CUST_HASH.
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.

CREATE GENERATOR gen_customer;

set GENERATOR gen_customer to 100;

CREATE TRIGGER customer_autoinc for customer
  BEFORE INSERT as
begin
  if (NEW.cust_hash is NULL) then
    NEW.cust_hash = GEN_ID(gen_customer, 1);
end;

<< Back to main page