创建索引(在 oracle DB 中),仅当它不存在时
Create index (in oracle DB), only if it does not exist
我想创建以下索引
CREATE INDEX timevariable_idx_varvalue_projectid
ON timevariable (varvalue,projectid);
only if 不存在,但我很难做到
有人知道怎么做吗?!
不幸的是,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 命令中没有 "IF NOT EXISTS" 语法。如果执行 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;
我想创建以下索引
CREATE INDEX timevariable_idx_varvalue_projectid
ON timevariable (varvalue,projectid);
only if 不存在,但我很难做到 有人知道怎么做吗?!
不幸的是,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 命令中没有 "IF NOT EXISTS" 语法。如果执行 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;