Oracle - 仅在不存在时创建索引

时间:2017-06-14 08:40:04

标签: oracle database-indexes

有没有办法在oracle中创建索引只有它们不存在?

这样的东西
CREATE INDEX IF NOT EXISTS ord_customer_ix
   ON orders (customer_id);

2 个答案:

答案 0 :(得分:10)

仅在不存在的情况下添加索引:

declare 
  already_exists  exception; 
  columns_indexed exception;
  pragma exception_init( already_exists, -955 ); 
  pragma exception_init(columns_indexed, -1408);
begin 
  execute immediate 'create index ord_customer_ix on orders (customer_id)'; 
  dbms_output.put_line( 'created' ); 
exception 
  when already_exists or columns_indexed then 
  dbms_output.put_line( 'skipped' );  
end;     

答案 1 :(得分:1)

如果不存在,则在Oracle中创建索引。

ALTER SESSION SET CURRENT_SCHEMA = PROD_INTG;
DECLARE
  INDEX_EXISTS NUMBER;
BEGIN
  SELECT COUNT(1)
  INTO INDEX_EXISTS
  FROM ALL_INDEXES AI,
    ALL_IND_COLUMNS AIC
  WHERE AI.TABLE_OWNER = 'PROD_INTG'
        AND AI.TABLE_NAME = 'PROCESS_APPLICATION'
        AND AI.INDEX_NAME = AIC.INDEX_NAME
        AND AI.OWNER = AIC.INDEX_OWNER
        AND AIC.COLUMN_NAME IN ('PST_CODE', 'PIZ_TYPE_ID');
  IF (INDEX_EXISTS) > 0
  THEN
    DBMS_OUTPUT.PUT_LINE('INDEX EXISTS  :');
  ELSE
    EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA = PROD_INTG';
    EXECUTE IMMEDIATE 'CREATE INDEX PROD_INTG.IDX_IQC_APPS_IN_PROC_PST_PIZ
      ON PROD_INTG.PROCESS_APPLICATION (PST_CODE, PIZ_TYPE_ID) PARALLEL 16';
    EXECUTE IMMEDIATE 'ALTER INDEX PROD_INTG.IDX_IQC_APPS_IN_PROC_PST_PIZ NOPARALLEL';
    DBMS_OUTPUT.PUT_LINE('INDEX created  :');
  END IF;
  EXCEPTION
  WHEN OTHERS THEN
  IF SQLCODE IN (-2275, -955, -02431, -01430, -01451, -01408)
  THEN
    NULL;
  ELSE
    RAISE;
  END IF;
END;
/