Check table exist or not before create it in Oracle

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

    My solution is just compilation of best ideas in thread, with a little improvement. I use both dedicated procedure (@Tomasz Borowiec) to facilitate reuse, and exception handling (@Tobias Twardon) to reduce code and to get rid of redundant table name in procedure.

    DECLARE
    
        PROCEDURE create_table_if_doesnt_exist(
            p_create_table_query VARCHAR2
        ) IS
        BEGIN
            EXECUTE IMMEDIATE p_create_table_query;
        EXCEPTION
            WHEN OTHERS THEN
            -- suppresses "name is already being used" exception
            IF SQLCODE = -955 THEN
                NULL; 
            END IF;
        END;
    
    BEGIN
        create_table_if_doesnt_exist('
            CREATE TABLE "MY_TABLE" (
                "ID" NUMBER(19) NOT NULL PRIMARY KEY,
                "TEXT" VARCHAR2(4000),
                "MOD_TIME" TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ');
    END;
    /
    

提交回复
热议问题