Mega Code Archive

 
Categories / Delphi / Examples
 

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