Hello,
I am using FirebirdSQL 2.5.9 on Windows OS.
There are some old versions of tables without a primary key. Most users already have that primary key added in their version of tables. I must add primary keys to missing tables only. There is an automatic database update system which runs SQL scripts. These scripts have to be completed without any error. I have to use that automatic database update system to convert all old version tables into new versions.
I can *manually* run below SQL script and it adds the required primary key and necessary trigger in a table:
/* ORDERS */
create sequence gen_orders_id;
alter table orders add x_orderid integer not null;
commit;
alter table orders alter x_orderid position 1;
update orders set x_orderid = gen_id(gen_orders_id, 1);
commit;
update rdb$relation_fields set rdb$null_flag = 1 where rdb$field_name = 'X_ORDERID' and rdb$relation_name = 'ORDERS';
commit;
alter table orders add constraint pk_orders primary key(x_orderid);
commit;
create or alter trigger orders_bi for orders
active before insert position 0
as
begin
if (new.x_orderid is null) then
new.x_orderid = gen_id(gen_orders_id,1);
end;
commit;
Above script gives an error if the primary key exists. Then I tried to use it in an execute block. That failed because I could not use "commit" in the execute block statement. My failed script right now is as following:
set term ^ ;
execute block as
begin
if (not exists(select 1 from rdb$relation_fields rf where rf.rdb$relation_name = 'ORDERS' and rf.rdb$field_name = 'X_ORDERID')) then
begin
execute statement 'create sequence gen_orders_id;';
execute statement 'alter table orders add x_orderid integer not null;';
execute statement 'commit;';
execute statement 'alter table orders alter x_orderid position 1;';
execute statement 'update orders set x_orderid = gen_id(gen_orders_id, 1);';
execute statement 'update rdb$relation_fields set rdb$null_flag = 1 where rdb$field_name = ''X_ORDERID'' and rdb$relation_name = ''ORDERS'';';
execute statement 'alter table orders add constraint pk_orders primary key(x_orderid);';
execute statement 'create or alter trigger orders_bi for orders active before insert position 0 as begin if (new.x_orderid is null) then new.x_orderid = gen_id(gen_orders_id,1); end;';
execute statement 'commit;';
end
end^
set term ; ^
That script gives the error "Explicit transaction control is not allowed At block line: 7, col: 5". If I remove the "commit" lines above, this time I get "Dynamic SQL Error SQL error code = -206 Column unknown X_ORDERID At line 1, column 19" error.
It has to be a script executing without any errors for my case. Is it possible what I am trying to do?
Any help is appreciated.
Thanks & Regards,
Ertan Küçükoğlu