我想创建以下索引
CREATE INDEX timevariable_idx_varvalue_projectid
ON timevariable (varvalue,projectid);
只有当不存在时,但我很难做到 有人知道该怎么做吗?!
不幸的是,Oracle 不支持CREATE
语句的IF NOT EXISTS
子句(虽然我不知道 APEX,但您也用它标记了您的问题(。
因此,您需要在代码块中execute immediate
。这篇 Ask TOM 文章提供了一个优雅的解决方案,它通过捕获异常来工作。
根据您的用例进行调整,这将是:
set serveroutput on
declare
already_exists exception;
columns_indexed exception;
pragma exception_init(already_exists, -955);
pragma exception_init(columns_indexed, -1408);
begin
execute immediate 'create index timevariable_idx_varvalue_projectid ON timevariable (varvalue,projectid)';
dbms_output.put_line('created');
exception
when already_exists or columns_indexed then
dbms_output.put_line('skipped');
end;
Oracle 在其 DDL 命令中没有"如果不存在"语法。如果执行 CREATE 命令,则需要接受脚本中的错误作为可以忽略的错误,或者以某种方式处理错误。如果你想避免执行推荐,除非必要,你需要先检查索引的数据字典,然后在需要时执行:
declare
l_count number;
begin
select count(*) into l_count from dba_indexes where index_name='TIMEVARIABLE_IDX_VARVALUE_PROJECTID';
if l_count = 0 then
execute immediate 'CREATE INDEX timevariable_idx_varvalue_projectid ON timevariable (varvalue,projectid)';
end if;
end;