Check table exist or not before create it in Oracle

前端 未结 8 1301
清酒与你
清酒与你 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:32

    I know this topic is a bit old, but I think I did something that may be useful for someone, so I'm posting it.

    I compiled suggestions from this thread's answers into a procedure:

    CREATE OR REPLACE PROCEDURE create_table_if_doesnt_exist(
      p_table_name VARCHAR2,
      create_table_query VARCHAR2
    ) AUTHID CURRENT_USER IS
      n NUMBER;
    BEGIN
      SELECT COUNT(*) INTO n FROM user_tables WHERE table_name = UPPER(p_table_name);
      IF (n = 0) THEN
        EXECUTE IMMEDIATE create_table_query;
      END IF;
    END;
    

    You can then use it in a following way:

    call create_table_if_doesnt_exist('my_table', 'CREATE TABLE my_table (
            id NUMBER(19) NOT NULL PRIMARY KEY,
            text VARCHAR2(4000),
            modified_time TIMESTAMP
      )'
    );
    

    I know that it's kinda redundant to pass table name twice, but I think that's the easiest here.

    Hope somebody finds above useful :-).

提交回复
热议问题