Oracle: If Table Exists

后端 未结 15 1307
无人共我
无人共我 2020-11-22 13:32

I\'m writing some migration scripts for an Oracle database, and was hoping Oracle had something similar to MySQL\'s IF EXISTS construct.

Specifically, w

相关标签:
15条回答
  • 2020-11-22 14:24

    Another method is to define an exception and then only catch that exception letting all others propagate.

    Declare
       eTableDoesNotExist Exception;
       PRAGMA EXCEPTION_INIT(eTableDoesNotExist, -942);
    Begin
       EXECUTE IMMEDIATE ('DROP TABLE myschema.mytable');
    Exception
       When eTableDoesNotExist Then
          DBMS_Output.Put_Line('Table already does not exist.');
    End;
    
    0 讨论(0)
  • 2020-11-22 14:24

    You could always catch the error yourself.

    begin
    execute immediate 'drop table mytable';
    exception when others then null;
    end;
    

    It is considered bad practice to overuse this, similar to empty catch()'es in other languages.

    Regards
    K

    0 讨论(0)
  • 2020-11-22 14:25
    BEGIN
       EXECUTE IMMEDIATE 'DROP TABLE "IMS"."MAX" ';
    EXCEPTION
       WHEN OTHERS THEN
          IF SQLCODE != -942 THEN
             RAISE;
              END IF;
             EXECUTE IMMEDIATE ' 
      CREATE TABLE "IMS"."MAX" 
       (    "ID" NUMBER NOT NULL ENABLE, 
        "NAME" VARCHAR2(20 BYTE), 
         CONSTRAINT "MAX_PK" PRIMARY KEY ("ID")
      USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 
      STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
      PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
      TABLESPACE "SYSAUX"  ENABLE
       ) SEGMENT CREATION IMMEDIATE 
      PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
      STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
      PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
      TABLESPACE "SYSAUX"  ';
    
    
    END;
    

    // Doing this code, checks if the table exists and later it creates the table max. this simply works in single compilation

    0 讨论(0)
提交回复
热议问题