How to make a repeatable index script?

I am trying to create a Firebird script that ensures that a specific index exists and is created correctly. After a bit of googling, I got what seems to be the correct syntax:

SET TERM ^ ;
execute block as begin
IF (EXISTS(SELECT RDB$INDEX_NAME
  FROM RDB$INDICES
 WHERE RDB$RELATION_NAME='TABLE_NAME'
 and RDB$INDEX_NAME = 'INDEX_NAME')) THEN
execute statement 'drop index INDEX_NAME';
end
SET TERM ; ^

CREATE UNIQUE INDEX INDEX_NAME
  ON TABLE_NAME
  (FIELD1, FIELD2, FIELD3);

This will work once and it works great. But if I try to run it a second time, I get an "index already exists" error, which indicates that the part execute statementis not actually running.

What am I missing? How to make this script work right?

+5
source share
2 answers

Use the WITH AUTONOMOUS TRANSACTION clause . The following code works for me:

EXECUTE BLOCK
AS BEGIN
  IF (EXISTS(SELECT RDB$INDEX_NAME FROM RDB$INDICES
    WHERE RDB$RELATION_NAME = '<relation_name>'
      AND RDB$INDEX_NAME = '<index_name>')) THEN
  BEGIN 
    EXECUTE STATEMENT 'drop index <index_name>'
      with autonomous transaction;
  END

  EXECUTE STATEMENT 'create index <index_name> on ...'
    with autonomous transaction;
END
+7
source

Did you complete the transaction?

. commit rollback, .

drop index foo

commit -- some implementations use 'commit work' others 'commit transaction'

create index foo on bar ( col_1 , ... , col_n )

commit -- some implementations use 'commit work' others 'commit transaction'
+5

All Articles