Oracle - Create an index only if not exists

半城伤御伤魂 提交于 2021-02-08 14:38:28

问题


Is there any way to create indexes in oracle only if they don't exists ?

Something like

CREATE INDEX IF NOT EXISTS ord_customer_ix
   ON orders (customer_id);

回答1:


Add an index only if not exists:

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;     



回答2:


CREATE INDEX IN ORACLE IF NOT EXISTS.

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


来源:https://stackoverflow.com/questions/44539663/oracle-create-an-index-only-if-not-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!