Subject Re: [firebird-support] A bit strange GEN_ID result
Author Paul Vinkenoog
Hi ionokot_k,

> In order to get the last inserted id I made this stored as a test:
>
> CREATE PROCEDURE NEW_PROCEDURE
> AS
> declare variable var integer;
> BEGIN
> select max(GEN_ID("Table1_ID_GEN",1)) FROM "Table1" INTO :var;
> insert into "Table1" ("ID") VALUES (:var);
> SUSPEND;
> END

That's not how to get the last inserted id. You either select the
new generator value (if you need one), like this:

select gen_id( "Table1_ID_GEN", 1 ) from rdb$database

or you select the max ID value from the table (if you need it):

select max( "ID" ) FROM "Table1"

If you select a gen_id() from a table with more then one record, the
generator will fire multiple times. In your case, all the newly
generated values except the last one are lost (because you select
the MAX). This explains the gaps:

> Calling this procedure more than three times the generated
> id are not "linear":
>
> Table1
> ID
> row1 1 OK
> row2 2 OK
> row3 3 OK
> row4 5 huh?
> row6 7 !!!
> row7 11 what the hell?
> row8 16 but...
> row9 22 #@?ยง#!!

One thing I can't explain is why the first gap occurs after row 3. It
"should" have occurred already after row 2.

Anyway, this procedure doesn't make much sense.

> With an
> "INSERT INTO "Table1" ("ID") VALUES (GEN_ID("Table1_ID_GEN",1))
> works fine...

Yes, that's how to do it!


Greetings,
Paul Vinkenoog