Check table exist or not before create it in Oracle

前端 未结 8 1155
清酒与你
清酒与你 2021-02-01 03:07

Trying to check is table exist before create in Oracle. Search for most of the post from Stackoverflow and others too. Find some query but it didn\'t work for me.



        
8条回答
  •  北海茫月
    2021-02-01 03:37

    As Rene also commented, it's quite uncommon to check first and then create the table. If you want to have a running code according to your method, this will be:

    declare
    nCount NUMBER;
    v_sql LONG;
    
    begin
    SELECT count(*) into nCount FROM dba_tables where table_name = 'EMPLOYEE';
    IF(nCount <= 0)
    THEN
    v_sql:='
    create table EMPLOYEE
    (
    ID NUMBER(3),
    NAME VARCHAR2(30) NOT NULL
    )';
    execute immediate v_sql;
    
    END IF;
    end;
    

    But I'd rather go catch on the Exception, saves you some unnecessary lines of code:

    declare
    v_sql LONG;
    begin
    
    v_sql:='create table EMPLOYEE
      (
      ID NUMBER(3),
      NAME VARCHAR2(30) NOT NULL
      )';
    execute immediate v_sql;
    
    EXCEPTION
        WHEN OTHERS THEN
          IF SQLCODE = -955 THEN
            NULL; -- suppresses ORA-00955 exception
          ELSE
             RAISE;
          END IF;
    END; 
    /
    

提交回复
热议问题