仅在不存在索引时创建索引(在oracle DB中]

问题描述 投票:1回答:2

我想创建以下索引

CREATE INDEX timevariable_idx_varvalue_projectid 
    ON timevariable (varvalue,projectid);

只有不存在,但我很难这么做有人知道怎么做吗!!

oracle oracle11g oracle10g oracle-apex ddl
2个回答
1
投票

[不幸的是,Oracle不支持IF NOT EXISTS语句的CREATE子句(尽管我不知道APEX,您也用APEX标记了问题)。

所以您需要在代码块中输入execute immediateAsk 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;  

0
投票

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;
© www.soinside.com 2019 - 2024. All rights reserved.