5

我正在尝试构建一个 Firebird 脚本,以确保某个索引存在并正确创建。经过一番谷歌搜索,我得到了似乎正确的语法:

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);

这将运行一次,并且工作正常。但是,如果我再次尝试运行它,我会收到“索引已存在”错误,这表明该execute statement部件实际上并未运行。

我错过了什么?如何使此脚本正常工作?

4

2 回答 2

7

使用WITH AUTONOMOUS TRANSACTION子句。以下代码适用于我:

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
于 2012-08-25T12:31:46.653 回答
5

提交交易了吗?

大多数关系数据库默认在事务中运行。直到您commitrollback交易未决。你需要

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'
于 2012-08-24T23:59:04.240 回答