Subject Re: [firebird-support] New auto-increment column, existing data
Author Alan J Davies
There are a few things missing from your setup.
Try this; there may be other ideas for you too, but this works.
create a new table

CREATE TABLE A_AUTO_TEST (
NEW_FIELD INTEGER NOT NULL,
SOME_DATA CHAR(10)
);

ensure the field you want is the PK

ALTER TABLE A_AUTO_TEST ADD CONSTRAINT PK_A_AUTO_TEST PRIMARY KEY
(NEW_FIELD);

create a generator - that does the auto-increment for you

CREATE SEQUENCE GEN_A_AUTO_TEST_ID;
change it to whatever you want
ALTER SEQUENCE GEN_A_AUTO_TEST_ID RESTART WITH 3;

create a trigger, I've used a before insert

SET TERM ^ ;

/* Trigger: A_AUTO_TEST_BI0 */
CREATE OR ALTER TRIGGER A_AUTO_TEST_BI0 FOR A_AUTO_TEST
ACTIVE BEFORE INSERT POSITION 0
AS
begin
new.new_field=gen_id(gen_a_auto_test_id,1);
end
^

SET TERM ; ^

now go ahead and insert data

insert into a_auto_test (some_data)
values('a2')

Hope this helps.

Alan J Davies
Aldis

On 15/11/2016 19:58, 'Some One' anotherpersonsomewhere@...
[firebird-support] wrote:
>
>
> I am trying to add new auto-increment primary keys for existing table.
>
> This is what I have:
> ======================================
> set term ~ ;
> execute block
> as
> declare dbkey char(8);
> begin
> for
> select rdb$db_key
> from mytable
> into :dbkey
> do
> begin
> ...
> end
> end~
> set term ; ~
> ======================================
> This fails with error "malformed string", it looks like either
> rdb$db_key does not match char(8) or maybe it is related to same
> character set settings. Any suggestions?
>
> It also seems that when new entries are added the auto-incremented
> values will start from 0, causing conflicts. Is it ok to simply right
> click the generator in FlameRobin, select "set value" and enter a value
> higher than the highest existing or will that cause any trouble?
>
>