Subject Re: [IBO] Primary Key->AutoInc Trigger Chicken & the Egg problem.
Author Helen Borrie
At 08:22 AM 05-02-01 -0600, you wrote:
>I am using a IBOTable Component and I have a primary key that gets generated
>in a before insert trigger. Here is the trigger code:
>
>CREATE TRIGGER INSERT_CREATE_DATE FOR "Customers"
>ACTIVE BEFORE INSERT POSITION 0
>as
>begin
> NEW.CREATE_DATE = 'NOW';
> NEW.EDIT_DATE = NEW.CREATE_DATE;
> NEW.CUST_NO = GEN_ID(gen_nextcustno, 1);
>end
>
>I have a form with a TDBText field for the CUST_NO (Primary Key) field and
>I've defined the CUST_NO TIntegerField->AutoGenerateValue as arAutoInc (I've
>tried arDefault too). The problem is that when I attempt to append a new
>record the following code is throwing an exception that says the CUST_NO
>must be defined:
>
>procedure TIBODataset.Post;
>begin
> if not FIsPosting then
> try
> FIsPosting := true;
> inherited Post;
> if State = dsSetKey then
> PostKeyBuffer( true ); // Exception thrown here!
> finally
> FIsPosting := false;
> end;
>end;
>
>How do I eliminate this. I'd prefer to leave the task of assigning the key
>value up to the database's trigger code. If that is possible, how do I
>retrieve the CUST_NO key value after I've posted the record?


Use the GeneratorLinks property and read FieldByName in the AfterPost event.

Change the trigger to this:

CREATE TRIGGER INSERT_CREATE_DATE FOR "Customers"
ACTIVE BEFORE INSERT POSITION 0
as
begin
NEW.CREATE_DATE = 'NOW';
NEW.EDIT_DATE = NEW.CREATE_DATE;
if (new.Cust_No is null) then
NEW.CUST_NO = GEN_ID(gen_nextcustno, 1);
end

Reserve the firing of the trigger to interactive work; or perhaps for
batch work like pumping.

If you want to get the value *before* you post the insert, remove the
GeneratorLinks setting and call the Gen_ID() method in the AfterInsert
event, i.e.

with myDataset.InternalDataset do
begin
FieldByName('CUST_NO').AsInteger := Gen_ID(gen_nextcustno, 1);
...
end;

I guess you know that cancelling the transaction doesn't "roll back" the
generator. The number stays generated.

Helen


All for Open and Open for All
InterBase Developer Initiative ยท http://www.interbase2000.org
_______________________________________________________